我正在尝试编写JavaScript函数,其中计数器应该每秒递增计数,并且一旦计数器在onClick()之后达到输入字段中的给定数字就应该停止。此外,当计数器可被3整除时,我想突出显示box1。当计数器可被5整除时,突出显示Box2。
JavaScript的:
$(document).ready(function () {
var number = parseInt($('#test').text(), 10) || 0; // Get the number from paragraph
// Called the function in each second
var interval = setInterval(function () {
$('#test').text(number++); // Update the value in paragraph
if (number > 5) {
clearInterval(interval); // If exceeded 100, clear interval
}
}, 1000); // Run for each second
});
HTML:
<form>
Enter the Number <br>
<input type="number" placeholder="Number" value="input" id="text">
<button type="button" value="Submit" id="tmsec"></button>
<p id="test"></p>
</form>
<div>
<div class="box">
<p>Finger</p>
</div>
<div class="box">
<p>Toes</p>
</div>
</div>
<button type="button"> Reset </button>
<button type="button"> Restart </button>
答案 0 :(得分:0)
我会这样做:
var MAX = 999;
$(document).ready(function () {
var number = parseInt($('#test').text(), 10) || 0;
var interval = setInterval(function () {
number++;
var max = $('#text').val() || MAX;
$('#box1').css('background-color', number % 3 === 0 ? 'red' : '');
$('#box2').css('background-color', number % 5 === 0 ? 'red' : '');
$('#test').text(number);
if (number >= max) {
clearInterval(interval);
}
}, 1000);
$('#test').text(number);
});
我还在框中添加了id:
<div class="box" id="box1">
<p>Finger</p>
</div>
<div class="box" id="box2">
<p>Toes</p>
</div>