如何在一页上有多个时钟?

时间:2018-10-25 10:41:16

标签: javascript

我有一个有效的 javascript 代码,但我希望在一个页面上有多个时钟。 例如,我需要3个时钟。 我不知道如何在getelementbyid中使用多个ID?

<div id="time">October 25, 2018 18:00 GMT+0300 (CDT)</div>



var timestamp = document.getElementById('time'),
t         = new Date(timestamp.innerHTML),
hours     = t.getHours(), 
min       = t.getMinutes() + '', 

months    = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

if(min.length == 1) min = '0' + min;
timestamp.innerHTML =  hours + ':' + min ;

1 个答案:

答案 0 :(得分:1)

每个人的回答都是正确的,我只是认为,如果您看到一些代码来引用他们在说什么,这将会有所帮助

var timestamp1 = document.getElementById('time1')
getTime(timestamp1)
var timestamp2 = document.getElementById('time2')
getTime(timestamp2)
var timestamp3 = document.getElementById('time3')
getTime(timestamp3)

    function getTime(obj){
        t = new Date(obj.innerHTML),
        hours = t.getHours(), 
        min = t.getMinutes() + '', 
       
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        if(min.length == 1){
             min = '0' + min;
         }

        obj.innerHTML =  hours + ':' + min;
    }
<div id="time1">October 25, 2018 18:00 GMT+0300 (CDT)</div>
<div id="time2">October 25, 2018 18:00 GMT+0300 (CDT)</div>
<div id="time3">October 25, 2018 18:00 GMT+0300 (CDT)</div>

请告诉我这是否有帮助!谢谢!