1

我正在使用 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 基于选择器选择适当的源和自定义函数?

4

1 回答 1

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作为key。

   $( "#birds,#turtles" ).autocomplete({
      source: "search.php",
      minLength: 2,
      select: function( event, ui ) {
        this.execute();
        completions[event.target.id]();
      }
    });
于 2013-02-06T10:39:35.437 回答