javascript - GetElementsByClassname 和 GetElementByID 的问题

标签 javascript html counter

我正在倒计时。

我的 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/

相关文章:

javascript - 如何在 javascript 中获取 svg 嵌入代码?

javascript - 网站已创建但显示不安全消息

python - 循环嵌套列表字典以计算键的出现次数

node.js - 在 Node.js 中使用 i++ 时的全局变量安全

c++ - 计算字符串中的多字符字符

javascript - VueJs 模块构建失败 : Error: Couldn't find preset "@vue/app" relative to directory

javascript - 使用 JavaScript (Netlify Identity) 控制内容 : Content flashes in slow connections, 如何仅在登录检查后加载它?

javascript - 下划线模板未触发 Backbone 事件

html - 如何让字体大小自动适应手机版

html - 从 ul 中删除填充时如何将元素符号水平对齐到左侧?