使用each和函数的jQuery中$(this)的意外作用域



当我执行以下代码时,我希望相同的元素id会被提醒两次,但第一次是正确的,而第二次总是显示集合中第一个元素的名称。

$("div.someClass").each(function (index) {
  $(this).click(function () {
    alert($(this).attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert($(this).attr("id")); // Here i get the first element in of that class
    });
  });
});

为什么会这样?如何解决?我曾尝试将元素的名称传递到函数中,但没有成功。

$(this)保存在某个变量中,例如that,稍后在animate 中使用

$("div.someClass").each(function (index) {
  $(this).click(function () {
    alert($(this).attr("id")); // Here i get the actually clicked element
    var that = $(this);
    $.when($("div.someClass").animate({ }, 0)).then(function () {           
      alert(that.attr("id")); // Here i get the first element in of that class
      alert($(this).attr("id")); 
    });
  });
});

this的值在每次函数调用时都会自动更改。因此,除非多个函数调用共同有意保留this的特定值,方法是传入该值,然后在调用回调之前使用.apply().call()进行设置,否则情况会有所不同。Javascript遵循以下规则:

  • 如果进行方法调用,则this的值将设置为其方法所在的对象
  • 如果进行普通函数调用,则this设置为全局对象(通常为window
  • 如果使用fn.apply()fn.call(),则会根据第一个参数设置this

最简单的解决方案是将this的值保存在一个局部变量中,然后引用它。

$("div.someClass").each(function (index) {
  var self = $(this);
  self.click(function () {
    alert(self.attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert(self.attr("id")); // Here i get the first element in of that class
    });
  });
});

您需要访问每个函数的元素:http://api.jquery.com/each/

$("div.someClass").each(function (index, element) {
  $(element).click(function () {
    var $this = $(this);
    alert($this.attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert($this.attr("id")); // Here i get the first element in of that class
    });
  });
});

还有助于了解"这"的含义:https://developer.mozilla.org/en/JavaScript/Reference/Operators/thisjQuery可能会混淆您对"this"应该是什么的理解,以及它为事件处理所做的所有上下文更改。

最新更新