1

以下のコードでプラグインを作成しています。$(opts.section, this).animate を $(opts.section).animate に変更すると、希望どおりに動作しますが、セクション要素のすべてのインスタンスをアニメーション化するため、現在のインスタンスのみに影響を与えたい. 「これ」を追加すると、すべて一緒に機能しなくなります。

  $('.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。代入が隠されているだけです。

クロージャー/スコープの簡単な例: variable がある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();

「scoped」を「this」に置き換えたと想像してみてください。一般的なアイデアが得られるはずです(まるで誰かvar this = triggerElementが関数のスコープ内に設定されているかのようです。

于 2012-08-20T00:15:29.737 に答える