当我执行下面的代码时,我希望相同的元素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
});
});
});为甚麽呢?如何解决?我尝试将元素的名称传递给函数,但没有起作用。
发布于 2012-07-28 01:01:51
您需要访问每个函数的元素: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”应该是什么的理解,以及它为事件处理所做的所有上下文更改。
https://stackoverflow.com/questions/11692257
复制相似问题