gpt4 book ai didi

javascript - 如何为html中的多个元素设置相同的id

转载 作者:行者123 更新时间:2023-11-28 15:12:21 25 4
gpt4 key购买 nike

我想对运行时创建的 10 个元素使用倒计时器。每个元素都有过期时间,所以我想向用户显示剩余的过期时间。所以我使用 jquery 文件来执行此操作。所以我必须使用标签的 id 来显示剩余时间。当我使用它时对于一个元素它工作正常,但是当我将它用于多个元素时它只适用于第一个元素。我如何解决这个问题以显示所有元素的剩余时间

Jquery 文件

    //var count = 1000;
//var counter = setInterval(timer, 1000);
//function timer() {
// count -= 1;
// if (count==1000) {
// clearInterval(counter);
// }
// document.getElementById("num").innerHTML = count;
//}
function CountDown() {

this.start_time = "02:00:00:23";
this.target_id = "#timer";
this.name = "timer";
}

CountDown.prototype.init=function(){
this.reset();
setInterval(this.name+'.tick()',1000);
}
CountDown.prototype.reset=function(){
time = this.start_time.split(":");
this.days = parseInt(time[0]);
this.hours = parseInt(time[1]);
this.minutes=parseInt(time[2]);
this.seconds = parseInt(time[3]);
this.update_target();
}

CountDown.prototype.tick=function(){
if (this.seconds > 0 || this.minutes > 0 || this.hours > 0 ||this.days>0) {

if (this.hours == 0 && this.minutes == 0 && this.seconds == 0) {
this.days = this.days - 1;
this.hours = 23;
this.minutes = 59;
this.seconds = 59;
}
if (this.minutes == 0 && this.seconds==0) {
this.hours = this.hours - 1;
this.minutes = 59;
this.seconds = 59;
}
else if (this.seconds == 0) {
this.minutes = this.minutes - 1;
this.seconds = 59;
}
else {
this.seconds = this.seconds - 1;
}

}
this.update_target();
}

CountDown.prototype.update_target = function () {
seconds = this.seconds;
minutes = this.minutes;
hours = this.hours;
days = this.days;
if (seconds<10)
seconds = "0"+seconds;
if (minutes < 10)
minutes = "0"+ minutes;
if (hours < 10)
hours = "0" + hours;
if (days < 10)
days = "0" + days;
$(this.target_id).val(days+":"+hours+":"+minutes + ":" + seconds)
// $(this.target_id).val(this.minutes+":"+seconds)


}

Html




<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" id="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>

最佳答案

Id在html中是唯一的,使用类代替..更多元素可以具有相同的类

$('.yourClass') 

而不是

$('#yourId') 

.

 <script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" class="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>


function CountDown() {

this.start_time = "02:00:00:23";
this.target_id = ".timer";
this.name = "timer";
}

关于javascript - 如何为html中的多个元素设置相同的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35876159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com