当我执行下面的代码时,我希望相同的元素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 00:56:03
将$(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-28 01:00:19
每次调用函数时,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
    });
  });
});发布于 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
复制相似问题