2

当我执行以下代码时,我希望相同的元素 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
    });
  });
});

为什么会这样?如何解决?我尝试将元素的名称传递给函数,但它不起作用。

4

3 回答 3

4

的值this会在每次函数调用时自动更改。因此,除非多个函数调用合谋通过传入某个特定值来故意保留this它,然后在调用回调之前使用.apply().call()设置它,否则它会有所不同。Javascript 遵循以下规则:

  • 如果您进行方法调用,则 的值将this设置为其方法所在的对象。
  • 如果进行普通函数调用,this则设置为全局对象(通常window)。
  • 如果使用fn.apply()or 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
    });
  });
});
于 2012-07-27T17:00:19.053 回答
4

例如保存$(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")); 
    });
  });
});
于 2012-07-27T16:56:03.207 回答
2

您需要访问每个函数的元素: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
    });
  });
});

还有助于阅读“this”的含义:https ://developer.mozilla.org/en/JavaScript/Reference/Operators/this jQuery 可能会混淆您对“this”应该是什么的理解与所有上下文的变化它用于事件处理。

于 2012-07-27T17:01:50.743 回答