[英]counterup the numbers with setInterval (jQuery)
我試圖用set interval來計算數據屬性中定義的數字。 我的代碼在這里。
$( ".number" ).each(function(index) {
var INCREMENT = $(this).data('increment');
var START_VALUE = 0;
var count = 0;
count = INCREMENT;
$(this).html(count);
window.setInterval( function(index){
count += INCREMENT;
$('.number').html(count);
}, 1000);
});
我最初能夠獲得數字,但是使用setInterval,所有都使用數組中的第一個數字。
$('.number').html(count);
將設置所有匹配元素的innerHTML。
html()
或text()
來設置值 +
運算符將從DOM重新獲得的值轉換為數字 function update() { // For each of the `.number` element $(".number").html(function(index, oldHTML) { var increment = +$(this).data('increment') || 0; // Get the increament value and convert it to number or set to 0 if none return +oldHTML + increment; // Update the respective element }); } window.setInterval(update, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="number" data-increment="2"></div> <div class="number" data-increment="3"></div> <div class="number" data-increment="4"></div>
你的問題是這行$('.number').html(count);
這意味着它設置所有元素的number
等於計數。 你應該使用$(this)
代替。
$(".number").each(function (index) {
var currentNum = $(this);
var INCREMENT = $(this).data('increment');
var count = 0;
count = INCREMENT;
window.setInterval(function (index) {
count += INCREMENT;
currentNum.html(count);
}, 1000);
});
可能這是你想要的:
$( ".number" ).each(function(index) {
var INCREMENT = $(this).data('increment');
var START_VALUE = 0;
var count = 0;
count = INCREMENT;
var element = $(this);
$(this).html(count);
window.setInterval(function(index){
count += INCREMENT;
element.html(count);
}, 1000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.