我正在倒计时。
我的 html 中需要有同一项目的多个实例。 这是我的代码:
function test() {
// (AAAA,MM,DD,HH,mm,S));
var countDownDate = new Date(Date.UTC(2020,05,28,11,00,0));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementsByClassName("test").innerHTML = days + "<span>d</span> " + hours + "<span>h</span> "
+ minutes + "<span>m</span> " + seconds + "<span>s</span><br />";
// If the count down is over, write some text
if (distance < 0) {
document.getElementsByClassName("test").innerHTML = "Live <i class='fa fa-circle faa-flash animated'></i>";
}
}, 1000);
}
问题是,当我使用: document.getElementsByClassName("test")
时,我的 html 中没有任何内容,但是如果我使用: document.getElementByID("test")
然后它就可以工作了。
但我不需要使用 id,因为我需要该元素在同一个 html 中出现多次
最佳答案
如果你想使用className,那么你需要使用迭代
let items= document.getElementsByClassName("test");
for(let i = 0; i < items.length; i++) {
items[i].innerHTML = `your innerHTML here`;
}
关于javascript - GetElementsByClassname 和 GetElementByID 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618854/