首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

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
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11692257

复制
相关文章

相似问题

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