在具有 javascript 的单个页面上递减具有相同 class 的多个数字
Decrementing multiple numbers with the same class on a single page with javascript
我在一页上有 6 个数字,每个数字在其内部都有自己的 div,class 为 'interval'。我需要使用单个 javascript 方法减少 DIV 中每个整数的 innerHTML。这是 html:
<div class="timer">54</div>
<div class="timer">98</div>
<div class="timer">100</div>
<div class="timer">24</div>
<div class="timer">8</div>
<div class="timer">16</div>
这是我的尝试 JavaScript:
$(document).ready(function () {
var intervalCountDown = window.setInterval(decrementTimeRemaining, 1000);
function decrementTimeRemaining() {
$('.timer').html($(".timer").html() - 1);
}
});
预期输出(1 秒后)将是 53、97、99、23、7、15。这些数字每秒都会再次递减。相反,在第一秒之后,每个元素都带有定时器class变成53,然后都是并发递减
$('.timer').html(function(index, html) {
return html - 1;
});
在您的情况下,您还可以使用 .text(function)
:
$('.timer').text(function(index, text) {
return text - 1;
});
请注意,每个值都是一个字符串 "54"
、"98"
、...因此需要转换为数字,当使用一元减号 (-
) 运算符,但如果您使用一元加号 (+
) 运算符,则不会发生,因为它也是串联运算符:
"2" - 1 // 1
"2" + 1 // "21"
使用这个函数:
function decrementTimeRemaining() {
$('.timer').each(function(idx, value) {
$(value).html(parseInt($(value).html()) - 1);
});
}
在您的代码中,您没有选择所有 class 名称为 "timer" 的元素。您必须使用 jquery 中的 each
方法循环遍历所有元素,然后使用 $(this)
循环选择和更新当前字段。
使用以下代码片段。
<script>
window.setInterval(decrementTimeRemaining, 1000);
function decrementTimeRemaining() {
$('.timer').each(function(){
$(this).html(parseInt($(this).html()) - 1);
});
}
</script>
我在一页上有 6 个数字,每个数字在其内部都有自己的 div,class 为 'interval'。我需要使用单个 javascript 方法减少 DIV 中每个整数的 innerHTML。这是 html:
<div class="timer">54</div>
<div class="timer">98</div>
<div class="timer">100</div>
<div class="timer">24</div>
<div class="timer">8</div>
<div class="timer">16</div>
这是我的尝试 JavaScript:
$(document).ready(function () {
var intervalCountDown = window.setInterval(decrementTimeRemaining, 1000);
function decrementTimeRemaining() {
$('.timer').html($(".timer").html() - 1);
}
});
预期输出(1 秒后)将是 53、97、99、23、7、15。这些数字每秒都会再次递减。相反,在第一秒之后,每个元素都带有定时器class变成53,然后都是并发递减
$('.timer').html(function(index, html) {
return html - 1;
});
在您的情况下,您还可以使用 .text(function)
:
$('.timer').text(function(index, text) {
return text - 1;
});
请注意,每个值都是一个字符串 "54"
、"98"
、...因此需要转换为数字,当使用一元减号 (-
) 运算符,但如果您使用一元加号 (+
) 运算符,则不会发生,因为它也是串联运算符:
"2" - 1 // 1
"2" + 1 // "21"
使用这个函数:
function decrementTimeRemaining() {
$('.timer').each(function(idx, value) {
$(value).html(parseInt($(value).html()) - 1);
});
}
在您的代码中,您没有选择所有 class 名称为 "timer" 的元素。您必须使用 jquery 中的 each
方法循环遍历所有元素,然后使用 $(this)
循环选择和更新当前字段。
使用以下代码片段。
<script>
window.setInterval(decrementTimeRemaining, 1000);
function decrementTimeRemaining() {
$('.timer').each(function(){
$(this).html(parseInt($(this).html()) - 1);
});
}
</script>