无法获得$(本)在jQueryUI的自动完成工作 [英] Can't get $(this) working in jQueryUI autocomplete
问题描述
我试图创建一个使用jQueryUI的一个通用的自动完成脚本。自动完成应为每个工作:
I'm trying to create a generic autocomplete script using jQueryUI. The autocomplete should work for every:
<input type='text' class='autocomplete' id='foo'/>
<input type='text' class='autocomplete' id='bar'/>
...
现在我试图访问使用$(这)在源函数'富'和'酒吧',但提醒我总是未定义的时候。
Now I'm trying to access 'foo' or 'bar' in the source function using $(this), but when alerting I always get 'undefined'.
$('input.autocomplete').autocomplete({
source: function(req, add){
var id = $(this).attr('id');
alert(id);
}
});
我在做什么错了?
What am I doing wrong?
推荐答案
分别设置自动完成在您选择的每个项目,采用了封闭来保存相关元素的引用。类似如下:
Setup autocomplete separately for each item in your selection, using a closure to hold a reference to the relevant element. Something like the following:
$('input.autocomplete').each(function(i, el) {
el = $(el);
el.autocomplete({
source: function(req, add) {
var id = el.attr('id');
alert(id);
}
});
});
替代(编辑)
我不明白为什么还有就是使用这种电阻每()
:它的工作原理,在code是非常清晰可读,它不会引入与效率问题;但如果你决心要避免每()
,这里是一个替代...
I don't see why there is such resistance to using each()
: it works, the code is very clear and readable, and it introduces no issues with efficiency; but if you're determined to avoid each()
, here's an alternative...
*请注意:以下方法依赖(一点点),jQuery的自动完成功能的内部,所以我建议第一个选项...但选择权在你。
*PLEASE NOTE: the following approach relies (a little bit) on the internals of jQuery Autocomplete, so I'd recommend the first option... but the choice is yours.
$('input.autocomplete').autocomplete({
source: function(req, add) {
var id = this.element.attr('id');
alert(id);
}
});
});
这将工作,至少要等到/除非他们改变了方式源()
函数是从在自动完成$ C称为$ C>插件。
That will work, at least until/unless they change the way the source()
function is called from within the autocomplete
plugin.
所以,你有两个选择......每个人的东西。
So, you have two options... something for everyone.
这篇关于无法获得$(本)在jQueryUI的自动完成工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!