2016-05-08 67 views
2

我有每個函數,裏面我有step函數的動畫。 當我嘗試調用$(this)並調用當前每個選擇器 - 它不起作用,並給我一些對象(可能是動畫步進函數)jQuery - 在step-ofimate函數裏面瞭解`this`

我怎樣才能達到$(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

根本就沒有。你在'selector'中引用了你想要的對象,爲什麼你會堅持一遍又一遍地調用'$(domNode)'? **使用'選擇器'!** – Thomas

回答

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

它不工作,給我一些對象

thisstep會在呼叫傳遞給jQuery()對象{ counter: 0 }

您可以使用selector$(this)作爲選擇器至.animate();請使用now參數step函數在.text()呼叫處設置值counter。請注意,函數的fx對象也具有參考this元素的elem屬性。您可以使用在.animate()之外定義的對象在第一個參數上傳遞設置,使用對象上的值重置動畫屬性。

+運營商之前$(this).text()設置counter值爲Number

不確定預期效果是什麼,儘管thisstep應該是.each()迭代的當前元素。

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>


的問題使用類似的模式js,你可以設置selector作爲一個屬性傳遞給.animate()對象的elem,參考this.elemthis.counterstep功能。

$(".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>