2016-05-08 9 views
2

私はステップ関数でアニメーションしていますが、それぞれの関数を持っています。 $(this)を呼び出して現在のセレクタを呼び出そうとすると、機能しないオブジェクトが返されます(おそらくアニメーションステップ関数の)jQuery - ステップアニメーション機能内の `this`を理解します

$ )?各要素セレクタの?

私のコード:

$(".animateNumber").each(function(){ 
    var selector = $(this); 
    jQuery({ counter: 0 }).animate({ 
     counter: $(this).text() 
    }, { 
     step: function() { 
      // problem: the $(this) not working - if change to `selector` working 
      $(this).text(Math.ceil(this.counter)); 
     } 
    }); 
}); 
+0

だけでありません。あなたは 'セレクタ'に必要なオブジェクトへの参照を持っています、なぜあなたは '$(domNode)'を何度も何度も呼び出すと主張しますか? **セレクタを使う!** – Thomas

答えて

0
$(".animateNumber").each(function(i,v){ 
     jQuery({ counter: 0 }).animate({ 
      counter: $(v).text() 
     }, { 
      step: function() { 
       $(v).text(Math.ceil(this.counter)); 
      } 
     }); 
    }); 
0

それが動作してjQuery()への呼び出しで渡されたオブジェクト{ counter: 0 }だろうstepで私にいくつかのオブジェクト

thisを与えるものではありません。

selectorまたは$(this).animate()のセレクタとして使用できます。 nowパラメータをstepに設定してcounterの値を.text()に設定する機能があります。また、fxオブジェクト(step)にはthisという要素があり、elemというプロパティがあります。 .animate()の外で定義されたオブジェクトを使用して、最初に設定するパラメータを渡して、オブジェクトの値を使用してアニメーションプロパティをリセットすることができます。

$(this).text()の前に+オペレータを追加してcounterの値をNumberに設定します。

thisstep)は、.each()の繰り返しで現在の要素にする必要がありますが、期待される効果はありません。 jsに同様のパターンを使用して

var props = {from:0, to:100}; 
 
$(".animateNumber").each(function() { 
 
    $(this).animate({ 
 
     counter: props.to 
 
    }, { 
 
     step: function(now, fx) { 
 
      console.log(this, fx.elem) 
 
      $(this).text(Math.ceil(now)); 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
<div class="animateNumber">0</div> 
 
<div class="animateNumber">0</div> 
 
<div class="animateNumber">0</div>


質問で、あなたはstep機能でthis.elemthis.counterを参照し、.animate()に渡されたオブジェクトのプロパティelemとしてselectorを設定することができます。

$(".animateNumber").each(function() { 
 
    var selector = $(this); 
 
    jQuery({ 
 
    elem: selector, 
 
    counter: 0 
 
    }).animate({ 
 
    counter: +$(this).text() 
 
    }, { 
 
    step: function() { 
 
     // problem: the $(this) not working - if change to `selector` working 
 
     this.elem.text(Math.ceil(this.counter)); 
 
     console.log(this) 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
<div class="animateNumber">1</div> 
 
<div class="animateNumber">2</div> 
 
<div class="animateNumber">3</div>

関連する問題