问题描述
我的网站上有不止一个小盒子,每个小盒子都会在不同的时间开始倒计时。
如何减少数值每秒的计时器,模拟倒数计时器?
< p class =countdown> 15< / p>
使用这个javascript可以正确倒计时,但是每一个拍卖箱都会受到影响。你会如何建议我隔离定时器只作用于一个项目?
< script>
var sec = 15
var timer = setInterval(function(){
$('。auctiondiv .countdown')。text(sec--);
if(sec = = -1){
$('。auctiondiv .countdown')。fadeOut('slow');
clearInterval(timer);
}
},1000);
< / script>
请尝试以下操作,正确地为所选值减少计数。
$(document).ready(function(){
//更新计数器的函数所有具有类别计数器的元素
var doUpdate = function(){
$('。countdown')。each(function(){
var count = parseInt($(this).html( ));
if(count!== 0){
$(this).html(count - 1);
}
});
};
//安排更新每秒发生一次
setInterval(doUpdate,1000);
});
JSFiddle示例
注意:这将对具有倒计时
类的每个元素运行倒计时序列。如果你想让它对单个元素更加严格,你需要将选择符从 .countdown
更改为更加严格的内容。
< p id ='theTarget'> 15< p id ='theTarget'最简单的方法是添加一个id并直接引用该项目。 / p为H.
JavaScript在这里稍微复杂一点,因为您希望计时器最终关闭,因为
$(document).ready(function(){
var timer = setInterval(function(){
var count = parseInt($('#theTarget')。html());
if(count !== 0){
$('#theTarget')。html(count - 1);
} else {
clearInterval(timer);
}
},1000);
});
JSFiddle示例
I'll have more than one of these small boxes on my site, and each will start counting down at different times.
How can I decrease the numerical value of the timer per second, giving the simulation of a countdown timer?
<p class="countdown">15</p>
Using this javascript it correctly countsdown, but every single auctionbox is affected. How would you suggest I isolate the timer to act on only one item?
<script>
var sec = 15
var timer = setInterval(function() {
$('.auctiondiv .countdown').text(sec--);
if (sec == -1) {
$('.auctiondiv .countdown').fadeOut('slow');
clearInterval(timer);
}
}, 1000);
</script>
Try the following which will properly issue the count down for the selected values.
$(document).ready(function() {
// Function to update counters on all elements with class counter
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
// Schedule the update to happen once every second
setInterval(doUpdate, 1000);
});
JSFiddle Example
Note: This will run the count down sequence on every element which has the countdown
class. If you'd like to make it more restrictive to a single element you'll need to alter the selector from .countdown
to something more restrictive. The easiest way is to add an id and reference the item directly.
<p id='theTarget'>15</p>
The JavaScript is a little more complex here because you'll want the timer to eventually shut off since there's not much chance, or use, of element with a duplicate id being added
$(document).ready(function() {
var timer = setInterval(function() {
var count = parseInt($('#theTarget').html());
if (count !== 0) {
$('#theTarget').html(count - 1);
} else {
clearInterval(timer);
}
}, 1000);
});
JSFiddle Example
这篇关于如何用jQuery创建倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!