1

我正在使用下面的代码构建一个插件。如果我将 $(opts.section, this).animate 更改为 $(opts.section).animate 它也可以按我的意愿工作,但是它会为 section 元素的所有实例设置动画,并且我希望它只影响当前的. 一旦我将“这个”添加到它,它就会停止一起工作。

  $('.next', this).on({
    click: function() {
      if(count+2 <= totalElems) {
        count += 1;
        currentAnimationSpot += singleElem + opts.offset;
        $(opts.section, this).animate({
          left: -currentAnimationSpot
        });
      }
    }
  });

  $('.prev', this).on({
    click: function(){
      if(count != 1) {
        count-=1;
        currentAnimationSpot -= singleElem + opts.offset;
        $(opts.section, this).animate({
          left: -currentAnimationSpot
        });
      }
    }
  });  
4

1 回答 1

2

函数内部this与函数外部不同this。编辑:正如@FabricioMatte 的回答所说——“this在你的 $(".next", this) 处理程序的范围内引用了触发处理程序的元素”。

因此,您需要将外部存储this在一个单独的变量中,以便您可以在函数内部访问它。例如

var self=this;

$('.prev', this).on({
    click: function(){
      if(count != 1) {
        count-=1;
        currentAnimationSpot -= singleElem + opts.offset;
        // now use self here
        $(opts.section, self).animate({
          left: -currentAnimationSpot
        });
      }
    }
  });

尽管这起初看起来很奇怪,但实际上与您在函数的本地范围内分配新值时看到的行为相同,只是this分配被隐藏了。

闭包/作用域的快速示例:假设您有一个变量scoped,您可以复制如下行为:

var scoped = "Outer scope!";
var saved = scoped;

myfn() {
    var scoped = "Inner scope!";
    console.log("Inner `scoped` is " + scoped); // Inner `scoped` is Inner scope!
    console.log("Inner `saved` is " + saved);  // Inner `saved`` is Outer scope!
};

console.log("Outer scoped is: " + scoped); // Outer scope!
console.log("Outer saved is: " + saved); // Outer scope!
myfn();

想象一下你用“this”替换了“scoped”,你应该明白了(就好像有人设置var this = triggerElement在函数的范围内。

于 2012-08-20T00:15:29.737 回答