如何在我的HTML页面上显示JS值

时间:2013-07-20 10:00:47

标签: javascript html

我正在尝试在我的网站上获得三个不同的动态时区时钟。我在这个网站上找到了以下js代码(保存为myClocks.js并包含在我的html网站的标题中):

var clock1 = new Date();
var clock2 = new Date();
var clock3 = new Date();
clock2.setHours(clock2.getHours() + 3);
clock3.setHours(clock3.getHours() - 5);
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();

如何编写“显示”代码以在HTML页面上的任何位置显示它?例如,作为名为clocks的ID,如下所示:

  

纽约:02:12:02巴黎:17:01:24莫斯科:22:23:42

非常感谢提前。

3 个答案:

答案 0 :(得分:1)

<html><head></head><body>
<script language="javascript">
ourDate = new Date();
document.write("The time and date at your computer's location is: "
+ ourDate.toLocaleString() 
+ ".<br/>");
document.write("The time zone offset between local time and GMT is " 
+ ourDate.getTimezoneOffset() 
+ " minutes.<br/>");
document.write("The time and date (GMT) is: " 
+ ourDate.toGMTString() 
+ ".<br/>");
</script>
</body></html>

答案 1 :(得分:0)

innerHTML就是您所需要的。尝试类似:

window.onload = function(){ // It is important to wait till DOM is ready!
   var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
   document.getElementById("clocks").innerHTML = clocks_str ;
}

如果你想要它是动态的,请使用setInterval方法,如下所示:

 var clocks_interval;
 var clocks_box;

 window.onload = startClocks;

 function startClocks(){
    clocks_box = document.getElementById("clocks");
    clocks_interval = setInterval(updateClocks , 1000); // 1000 means 1 second
 }

 function updateClocks (){
    var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
    clocks_box.innerHTML = clocks_str ;
 }

答案 2 :(得分:0)

您可以创建div或其他HTML并使用“innerHTML”。

document.getElementById("clocks").innerHTML = clock1.getUTCHours();