使用;这";在jQuery中设置动画

使用;这";在jQuery中设置动画,jquery,jquery-animate,Jquery,Jquery Animate,我正在用下面的代码构建一个插件。如果我将$(opts.section,this).animate更改为$(opts.section)。animate也可以按我的需要工作,但它会为section元素的所有实例设置动画,并且我希望它只影响当前的实例。一旦我加上“this”,它就会停止工作 $('.next', this).on({ click: function() { if(count+2 <= totalElems) { count += 1;

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

  $('.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
        });
      }
    }
  });  
$('.next',this).on({
单击:函数(){

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

因此,您需要将外部
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
分配被隐藏了

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

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();

试想一下,您将“scoped”替换为“this”,您应该会得到大致的想法(这就好像有人在函数的作用域内设置了
var this=triggerement

这向我表明,匿名函数内的
this
指的是与函数外的
this
不同的东西。如果在函数外执行类似操作,会发生什么nd reference
self
?哇,它成功了!我已经想了好几个小时了。我仍然不明白为什么它不成功,用这个?如果你回答这个问题,我会给你答案。在
$('.next',this)
中,
this
是上下文(祖先)在处理程序内部,
这个
引用了触发处理程序的元素,
.next
元素。关于闭包/作用域和
这个
=]
@fabriciomatté,你对闭包/作用域有最喜欢的答案吗当我想解释这个概念时,很高兴能有一个链接与大家分享:)闭包和变量作用域一般都解释得很好(第一个投票最多的答案稍难理解,因此您可以开始阅读下面一些更简单的答案),现在我一直在寻找关于
这个
范围的一些具体材料,请检查。自以为是的旁注:这就是为什么我喜欢Python将
self
明确地包含在方法中作为参数的原因——它让您非常明确地了解每个变量的来源,而不是(非常小的改变
这个
的魔力)谢谢你的精彩解释。