我有一个网页,它将待办事项列表显示为独立的div/区段。每个待办事项上都有一个由JavaScript控制的倒计时时钟。我可以在我的待办事项列表中有多个项目,并希望多个倒计时时钟(每个项目一个)。
JS对列表中的第一项正确运行,但不对多项运行。如果我删除第一个项目的倒计时时钟,那么第二个项目的时钟显示并开始计数。
如何对待办事项列表中的每个项目使用相同的脚本?
我能否将它转换为循环中调用的函数,传递ID?我试过了,但没能成功。
下面是我最好的例子。
{% for todo in todo_list}
// div sections (each section should have its own independent countdown timer)
<div id="segment/{{todo.id}}">
<div id="diff-{{todo.id}}">
// JavaScript inside for loop
// Script to run for each item in todo list and update the div with time/expired based on the todo.id
<script>
var diff = document.getElementById('diff-{{todo.id}}');
var now = moment.utc().format("YYYY-MM-DD HH:mm:ss");
var input_time = '{{todo.created_on}}';
var exam_end_time ='{{todo.eta}}'
var mins = moment.utc(moment(exam_end_time, "HH:mm"),diff(moment(now, "HH:mm"))).format("mm")
var frequency = mins*60
var refreshIntervalId = setInterval(() => {
const formatted = moment.utc(frequency--*1000.format("mm:ss");
diff.innerHTML = formatted;
}, 1000;
setTimeout(() => {
if(mins === ) {
diff.innerHTML = "Expired";
clearInterval(refreshIntervalId);
}},frequency*1000;
</script>
</div>
</div>
{% endfor %}发布于 2022-07-15 03:40:15
在董事会的帮助下找到了解决方案。生命中的包装脚本如下所示。
{% for todo in todo_list}
// div sections (each section should have its own independent countdown timer)
<div id="segment/{{todo.id}}">
<div id="diff-{{todo.id}}">
// JavaScript inside for loop
// Script to run for each item in todo list and update the div with time/expired based on the todo.id
<script>
(function timer() {
var diff = document.getElementById('diff-{{todo.id}}');
var now = moment.utc().format("YYYY-MM-DD HH:mm:ss");
var input_time = '{{todo.created_on}}';
var exam_end_time ='{{todo.eta}}'
var mins = moment.utc(moment(exam_end_time, "HH:mm"),diff(moment(now, "HH:mm"))).format("mm")
var frequency = mins*60
var refreshIntervalId = setInterval(() => {
const formatted = moment.utc(frequency--*1000.format("mm:ss");
diff.innerHTML = formatted;
}, 1000;
setTimeout(() => {
if (mins === ) {
diff.innerHTML = "Expired";
clearInterval(refreshIntervalId);
}
},frequency*1000;
})()
</script>
</div>
</div>
{% endfor %}https://stackoverflow.com/questions/72987758
复制相似问题