【问题标题】:Unexpected scope for $(this) in jQuery using each and functionjQuery 中 $(this) 的意外作用域使用 each 和函数
【发布时间】:2012-07-27 16:54:11
【问题描述】:

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

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

【问题讨论】:

  • 当您单击一个 div 时,您希望所有具有相同类的 div 都进行动画处理吗?您正在重新选择 $.when 中的 div,因为只有在您获取集合中第一个项目的 id 属性时才会调用 .then 回调。

标签: jquery scope


【解决方案1】:

$(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")); 
    });
  });
});

【讨论】:

    【解决方案2】:

    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
        });
      });
    });
    

    【讨论】:

      【解决方案3】:

      你需要访问每个函数的元素: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-09-10
        • 2017-05-26
        • 1970-01-01
        • 2021-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-18
        • 1970-01-01
        相关资源
        最近更新 更多