2016-04-20 131 views
0

我有几个jQuery UI的对象,他们都有一个类似的回调:如何将参数传递给jQuery UI的回调函数

$(function() { 
    $("#my_list").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       type: "POST", 
       url: "api", 
       data: { 
        term: request.term, 
       }, 
       success: response, 
       dataType: 'json', 
       minLength: 0, 
      }); 

     }, 
     minLength: 0, 
     select: function(event, ui) { 
       $('something').appendTo("#another_list"); 
      } 

     } 
    }); 
}); 

如果我可以通过“my_list”和“another_list”有作为参数,则代码会更干净。 这怎么办?

+0

我不明白你想在哪个函数中得到“my_list”和“another_list”作为参数 – PaoloCargnin

回答

1

只是将该代码包装在函数中?

function initAutocomplete(list1, list2){ 
    $(list1).autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       type: "POST", 
       url: "api", 
       data: { 
        term: request.term, 
       }, 
       success: response, 
       dataType: 'json', 
       minLength: 0, 
      }); 

     }, 
     minLength: 0, 
     select: function(event, ui) { 
       $('something').appendTo(list2); 
      } 

     } 
    }); 
} 

$(function(){ 
    initiAutocomplete('#my_list', '#another_list'); 
    initiAutocomplete('#my_second_list', '#another_list_part_deux'); 
}); 
+0

这很好用。我只是有一个愚蠢的问题。我正确的说,jquery-ui使用回调签名$(function(){});并告诉它什么事件触发它(如点击事件)? – max

+1

'$(function(){})'是'$(document).ready'的缩写。它会在回调中执行任何代码之前等待dom完全加载。它并不特定于jquery-ui – PhilVarg

相关问题