我正在尝试用设置的时间间隔计算数据属性中定义的数字。 我的代码在这里。
$( ".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>
关于javascript - 使用 setInterval (jQuery) 计算数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32835001/