'this'在jQuery自定义方法中未定义

时间:2009-07-27 18:16:22

标签: jquery

我有一个方法,我想根据复选框的“已检查”状态采取一些操作。 'click'事件按预期工作,但foreach循环中的'myFunction'调用不会:

$(document).ready(function(){
  $('#TreeView1 :checkbox')
    .click(HandleCheckbox); // Works fine

  // Go through the entire Category treeview to 
  // see if there are any checkboxes that are already
  // checked.
  $.fn.myFunction = HandleCheckbox;
  $(":checked:checkbox").each(function(index) {
    // In the HandleCheckbox 'this' is undefined.
    $(this).myFunction(); 
  });

});

function HandleCheckbox() {
  alert(this.name + '=' + this.checked);
}

在上面的代码中,当'.click'方法触发时,'this'按预期定义。当我在foreach循环中调用'muFunction'时,'this'在'HandleCheckbox'函数中未定义。

我仍在学习jQuery绳索,所以如果有更好或更简单的方法,请告诉我。

感谢。

4 个答案:

答案 0 :(得分:6)

这也有效:

$(":checked:checkbox").each(HandleCheckbox)

答案 1 :(得分:3)

在javascript中,this指的是对象的所有者。对于事件,这是触发事件的对象。但是,对于来自所述函数/事件处理程序的被调用函数,不继承该属性。虽然人们可能认为它应该在你给出的例子中起作用,但我并不完全了解语言的复杂性,但我认为这是罪魁祸首。如果您想使用它,请传递this的引用,如下所示:

$(this).myFunction(this);

这让我想起,你可以通过使用:

解决这个问题
// this becomes the `this` "keyword" without defining a parameter to hold it
$(this).myFunction.apply(this);

答案 2 :(得分:1)

解决此范围问题的一般方法:

parent_func = this;
$(":checked:checkbox").each(function(index) {
  $(parent_func).myFunction(); 
});

答案 3 :(得分:0)

试试这个:

$("input:checkbox:checked").each(function(index) {
    $(this).myFunction.apply(this); 
  });