首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用each和函数的jQuery中$(this)的意外作用域

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

Stack Overflow用户
提问于 2012-07-28 00:54:11
回答 3查看 1.6K关注 0票数 2

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

代码语言:javascript
运行
复制
$("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
    });
  });
});

为甚麽呢?如何解决?我尝试将元素的名称传递给函数,但没有起作用。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-28 00:56:03

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

代码语言:javascript
运行
复制
$("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")); 
    });
  });
});
票数 4
EN

Stack Overflow用户

发布于 2012-07-28 01:00:19

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

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

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

代码语言:javascript
运行
复制
$("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
    });
  });
});
票数 4
EN

Stack Overflow用户

发布于 2012-07-28 01:01:51

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

代码语言:javascript
运行
复制
$("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”应该是什么的理解,以及它为事件处理所做的所有上下文更改。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11692257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档