为什么文本在没有for循环的情况下不断重复?

时间:2015-08-17 18:10:13

标签: javascript

我正在制作一个代码,根据所选的单选按钮提供两种不同类型的时钟。当时钟出现时,文本说“重新加载页面以返回时钟设置。但是,当选择12小时时钟单选按钮时,文本每秒重复一次。有没有办法解决这个问题?请不要使用J Query,我不知道。

function clock_12() {
	document.write("<div align='center' style = 'background:#420080; color:limegreen'>"+"Reload the page to go back to the clock settings."+"</div>");
	var clocktime = new Date();
	var hours = clocktime.getHours();
	var mins = clocktime.getMinutes();
	var secs = clocktime.getSeconds();
	var ampm = (hours >= 12) ? "P.M." : "A.M.";

	if (hours >= 13) {
		hours -= 12;
	}
	if (hours < 1) {
		hours = 12;
	}
	if (mins < 10) {
		mins = "0" +mins;
	}
	if (secs < 10) {
		secs = "0" +secs;		
	}
	document.write("<div id = 'the_clock' align = 'center' style = 'background:#420080; color:limegreen'></div>");
	var div_clock = document.getElementById("the_clock");
	div_clock.innerHTML = hours + ":" +mins+ ":" +secs+ " " +ampm;
	setTimeout("clock_12()", 1000);
}
function clock_24() {
	var clocktime = new Date();
	var hours = clocktime.getHours();
	var mins = clocktime.getMinutes();
	var secs = clocktime.getSeconds();
	var back = "Reload the page to go back to the clock settings.";
	document.writeln("<div align='center' style = 'background:#420080; color:limegreen'>"+back+"</div>");
	if (mins < 10) {
		mins = "0" +mins;
	}
	if (secs < 10) {
		secs = "0" +secs;		
	}
	document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");
	var div_clock = document.getElementById("clock");
	div_clock.innerHTML = hours + ":" +mins+ ":" +secs;
	setTimeout("clock_24()", 1000);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<title>12 and 24 Hour Clocks</title>
</head>

<body style="background:limegreen">
<table style="width:50%" align = "center">
	<tr>
		<td><script type = "text/javascript" src = "clock.js"></script></td>
	</tr>
	<tr>
		<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock12">12 Hour Clock</label><input type = "radio" onclick = "clock_12()" id = "clock12" value = "clock12"></td>
		<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock24">24 Hour Clock</label><input type = "radio" onclick = "clock_24()" id = "clock24" value = "clock24"></td>
	</tr>
</table>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你有一行

document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");

clock_24函数中,由于这个原因每秒调用一次:setTimeout("clock_24()", 1000);clock_12也是如此。因此,从您的函数中删除这些行。把它放在外面,就像文件clock.js的开头一样。查看http://www.w3schools.com/jsref/met_win_settimeout.asp

编辑:抱歉,这不止一行。您已将所有document.write放在功能之外。

编辑:roshen_amin正确地评论说html需要在点击时写。因此,完整的解决方案是创建一个执行document.write,然后calls clock_24() / clock_12()的函数。点击后,调用该功能而不是clock_24() / clock_12()。像这样,单击时会出现html,但每秒只会调用该函数的其余部分