使用超时在jQuery live / delegate中获取“this”元素ID

时间:2010-08-19 20:00:58

标签: javascript binding jquery

我试图获取用jQuery delegate()函数绑定的元素的ID。我想将元素的ID传递给另一个函数。返回的ID总是“未定义”,我不知道为什么。这是我的代码:

$(document).ready(function() {
  var timeout = undefined;
  $('body').delegate(
    '#tab-form input[type="text"]',
    'keypress',
    function(){
      if(timeout != undefined) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(function() {
        timeout = undefined;
        alert($(this).attr('id'));
      }, 500);
    }
  );
});

我的标记:

<form id="tab-form">
  <input type="text" value="" id="Tab_name" name="Tab[name]">
  <input type="text" value="" id="Tab_text" name="Tab[text]">
</form>

在文本输入中创建一个按键会弹出一个JS警告,显示“未定义”,而不是像我想象的那样“Tab_name”或“Tab_text”。

我最初的Google搜索引导我相信attr('id') undefined 的原因是“this”实际上不是单个DOM元素,而是一个数组delegate()附加到的元素。我无法弄清楚如何在jQuery对象数组中访问当前绑定元素的DOM对象。

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:2)

这是因为this不是你想要的那个匿名函数,它是window。有几种方法可以解决这个问题,例如使用$.proxy(),如下所示:

  timeout = setTimeout($.proxy(function() {
    timeout = undefined;
    alert(this.id);
  }, this), 500);

答案 1 :(得分:0)

上下文为window,因为window拥有setTimeout。只需缓存它:

$(document).ready(function() {
  var timeout = undefined;
  $('body').delegate(
    '#tab-form input[type="text"]',
    'keypress',
    function(){
      var el = this;
      if(timeout != undefined) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(function() {
        timeout = undefined;
        alert($(el).attr('id'));
      }, 500);
    }
  );
});

答案 2 :(得分:0)

meder已经指出了这种行为的原因。您也可以传递event object并使用target

$(document).ready(function() {
  var timeout = undefined;
  $('body').delegate(
    '#tab-form input[type="text"]',
    'keypress',
     function(event){
        if(timeout != undefined) {
           clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
           timeout = undefined;
           alert($(event.target).attr('id'));
     }, 500);
   }
 );
}); 

旁注:在文档上使用.delegate()。根本没有意义。您可以将这些事件与.live()绑定到您的元素。

答案 3 :(得分:0)

由于使用了其他选项,我将提供closure选项。 :O)

(function( th ) {
  timeout = setTimeout(function() {
    timeout = undefined;
    alert(th.id);
  }, 500);
})( this );

编辑:为了解释发生了什么,基本上你要创建一个函数,调用函数并同时将this作为参数传递给函数。 / p>

这样想:

  // Create a new function that accepts one argument
function myFunc( th ) {
  timeout = setTimeout(function() {
    timeout = undefined;
    alert(th.id);
  }, 500);
}

  // Immediately call the function, and pass "this" in to it
myFunc( this );

这是完全相同的事情。拿这个,将整个函数包装在()中,通过删除函数myFunc的名称使其匿名,然后从函数调用中取出执行运算符( this ),并直接放置它在功能之后。

当你这样做时,你基本上是在创建它之后调用函数。这只是一种立即执行未命名(匿名)函数的简单方法。