如何知道哪个选择器是活动的?

时间:2012-01-24 12:16:34

标签: jquery css-selectors jquery-autocomplete

我有以下(部分)代码:

$("#input1, #input2").autocomplete({
   source:function( request, response ) { 
     ...
   }, ...);

好的,我想知道如何知道source选项中哪个是选择器active,input1或input2。我尝试过使用$(this).attr(“id”),但它会抛出未定义的内容。

版本:在“select:”选项中,$(this).attr(“id”)工作正常。

3 个答案:

答案 0 :(得分:2)

这种解决方法应该没问题。 在自动完成插件的源函数中,$(this)可能不会引用原始jquery对象。

$("#input1, #input2").each(function(){
  var id = $(this).attr('id');
  // Do something with id if you want
  $(this).autocomplete({
   source:function( request, response ) { 
     // Source function
   });
});

答案 1 :(得分:2)

当您使用jQuery UI自动完成程序时,您可以从自动完成实例上的 未记录的 element属性中获取该元素:

source: function(request, response) {
  if (this.element && this.element[0]) {
    display("source triggered for #" + this.element[0].id);
  }
}

Live example

this.element是自动填充程序附加到的元素的jQuery包装器,因此this.element[0]是原始DOM元素。

但是使用未记录的信息总是有风险的,它可以在点发布之间改变或消失。使用SadullahCeran建议的封闭物会更可靠。我的做法略有不同:

$("#input1, #input2").each(function(){
  var $element = $(this); // `element` is a jQuery wrapper around the element
  $(element).autocomplete({
   source:function( request, response ) { 
     // get the options relevant to `element`
   });
});

...只是因为你不依赖于使用id值。但这是一个小问题。是的,上面确实最终创建了两个函数对象,但这并不是一件坏事。如果涉及到很多代码并且您担心在内存中有两个副本(这几乎肯定不是问题),只需将函数调用到另一个函数中:

$("#input1, #input2").each(function(){
  var $element = $(this); // `element` is a jQuery wrapper around the element
  $(element).autocomplete({
   source:function( request, response ) { 
     return getOptionsFor(element, request, response);
   });
});
function getOptionsFor(element, request, response) {
  // get the options for `element`
}

答案 2 :(得分:0)

我认为你需要的是$(this.element).attr(“id”)。在插件中(以及对于您传入的任何回调),这通常是指ui小部件对象。我相信目标是标准化ui小部件,以便除其他外,this.element将引用您使用的任何ui小部件的当前DOM节点。