有没有办法在自动完成源函数上获取输入元素? $(this)
没有引用自动完成实例的输入。
jsFiddle示例here。
<input type="text" data-code="foo" placeholder="type something ..." class="suggest" />
<input type="text" data-code="foo2" placeholder="type something ..." class="suggest" />
JavaScript
$(".suggest").autocomplete({
delay: 100,
source: function (request, response) {
// get foo here,: $(this).data("code"); not working
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data){
response(data[1]);
});
}
});
答案 0 :(得分:2)
this.element
获取源函数的当前元素。
$(".suggest").autocomplete({
delay: 100,
source: function (request, response) {
this.element.data("code");
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data){
response(data[1]);
});
}
});
工作样本here