我正在使用jqueryui自动完成功能。我想将自动完成绑定到各种选择器,但需要为不同的选择器自定义自动完成功能的成功,来源等。
//Define execute function for birds
//Define execute function for turtles
$( "#birds,#turtles" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
this.execute();
/*based on selector id execute() will call the
right function attached with the selector
if called by birds
call execute function of birds
if called by turtles
call execute function of turtles*/
}
});
那么如何将自定义函数与各种对象相结合,让jquery根据选择器选择合适的源和自定义函数?
答案 0 :(得分:2)
Event.target
将提供触发自动填充的DOM元素。
$( "#birds,#turtles" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
this.execute();
autocomplete(event, ui);
}
});
function autocomplete(event, ui){
if(event.target.id == "birds"){
//dothis();
}else if(event.target.id == "turtles"){
//dothat();
}
}
如果您想要更复杂的解决方案,您可以创建类似工厂的工厂。如:
var completions = {
turtles: function(){
//Do this
},
birds: function(){
//Do that
}
};
然后在绑定到select的函数中使用此对象,使用id作为键。
$( "#birds,#turtles" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
this.execute();
completions[event.target.id]();
}
});