1

jQuery v1.8.3 と jQuery UI v1.9.2 を使用しています。この方法でオートコンプリートウィジェットを実装しました。

$('#input_id').autocomplete({
  create: function (event, ui) {
    // Initialize data
    $(this).data( 'custom', { property1: 'Hello', property2: { num: 1, funct: function() { ... return value } } );

    alert($(this).data('custom').property1) // Display 'Hello'
  },

  select: function(event, ui) {
    alert($(this).data('custom').property1) // Display 'Hello'
  },

  source: function(request, response) {
    alert($(this).data('custom').property1) // Display 'undefined'
    alert(this.data('custom').property1)    // I get 'TypeError: this.data is not a function'
  }
});

なぜ私が中にsource入るオプションと私が得るイベントなのですか?オプションコンテキストでプロパティに適切にアクセスして取得するにはどうすればよいですか?undefinedcreateselectHellonumbersearchHello

4

1 に答える 1

3

this内部source関数は、関数内でデータを割り当てているINPUTではなく、匿名関数を参照しているように見えるため、ここでは未定義になっていcreateます。

関数内の入力にアクセスするには、他の手段を使用してくださいsource

$('#input_id').autocomplete({
    create: function (event, ui) {
        // when using "this" here, you're refering to #input_id input
    },
    source: function(request, response) {
        // when using "this" here, you're refering to anonymous function
    }
});

ソース関数内のデータにアクセスするには、次を使用します。

 // ...
 source: function(request, response) {
     // you don't need to wrap this.element in jQuery again since it is already wrapped
     this.element.data('custom').property1
 }

将来のクイックリファレンス用のデモ:http://jsbin.com/ojesig/1/edit

于 2012-12-06T12:59:08.607 に答える