2016-10-25 33 views
1

複数の要素に同時にEasyAutocompleteを使用しようとしました しかし、$(this)はいつも未定義ですか?

$("#city_selector_suggest, $city_two, #city_down").easyAutocomplete({ 
    url: "/templates/rm/js/ecity2.json", 

    getValue: function(element) { 
     return element.cdek_cityname; 
    }, 

    list: { 
     onChooseEvent: function() { 
      var selectedItemValue = $(this).getSelectedItemData().cdek_id; 
      console.log(selectedItemValue); 
     }, 
     match: { 
      enabled: true, 

      method: function(element, phrase) { 
       if(element.indexOf(phrase) === 0) { 
        return true; 
       } else { 
        return false; 
       } 
      } 
     } 
    } 
}); 
+1

私の推測では、イベントを要素にバインドしていないのです... 'console.log(this)'はおそらくウィンドウを表示しています。議論はあなたに何かを与えますか? – epascarello

+0

これはコード全体でこれがないことがわかります – EaBangalore

答えて

0

迅速試験、すなわち「jQueryのそれをしない好きではない」、EasyAutocompleteイベントハンドラでは、thisを従来にない使用されていることを示しています。私はjQueryプラグインから期待何

:イベントハンドラ・ポイントの内部

  • this DOM要素へ
  • イベントハンドラは、少なくとも一つのevent引数と、おそらく追加data引数を取得します。

    • thisウィジェット
    • の構成オブジェクトのいくつかの並べ替えであるイベントハンドラ

    ための引数がない構成オブジェクトはしていないようです:EasyAutocompleteが何

ウィジェット、またはウィジェットが基づいているDOM要素を取得する方法を提供します。

解決策に最も近いのは、.each()を使用し、ウィジェットを個別にバインドして、現在の要素への参照を格納することです。

$("#city_selector_suggest, #city_two, #city_down").each(function() { 
    var $self = $(this); 

    $self.easyAutocomplete({ 
     url: "/templates/rm/js/ecity2.json", 
     getValue: function(element) { 
      return element.cdek_cityname; 
     }, 
     list: { 
      onChooseEvent: function() { 
       var selectedItemValue = $self.getSelectedItemData().cdek_id; 
       console.log(selectedItemValue); 
      }, 
      match: { 
       enabled: true, 
       method: function(element, phrase) { 
        return element.indexOf(phrase) === 0; 
       } 
      } 
     } 
    }); 
}); 

ないのいずれか、一度だけ、ではなく、完全に恐ろしい.easyAutocomplete()を呼ぶほどエレガント。

関連する問題