我正在尝试在我的网站中实现Javascript / PHP / AJAX时钟,这样我就可以拥有一个可以在不同时区运行的简单时钟(教程在这里http://networking.mydesigntool.com/viewtopic.php?tid=373&id=31)
这本身工作正常,但我已经在页面上运行了一个javascript秒表,并且2似乎发生冲突,秒表工作时时钟不会显示。
这是时钟的脚本:
<script type="text/javascript">
function loadTime ()
{
http_request = false;
if(window.XMLHttpRequest)
{
// Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
}
else if(window.ActiveXObject)
{ // IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
var parameters = "time=";
http_request.onreadystatechange = alertContents;
http_request.open('POST', 'time.php', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
result = http_request.responseText;
document.getElementById('clock').innerHTML = result;
}
}
}
</script>
<body onload="setInterval('loadTime()', 200);">
这是秒表的代码:
<script type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1;
} else {
min = min;
}
if (min == 60) {
min = 0;
hour += 1;
}
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true;
}
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start";
}
window.clearTimeout(SD);
}
</script>
有人可以帮助我让他们并肩工作吗?
感谢您的帮助
答案 0 :(得分:1)
试试这个: 看到微妙的'+ ='而不是'='!
window.onload += function()
{
stopwatch('Start');
}
答案 1 :(得分:1)
首先,您要在HTML中声明onload
事件处理程序:
<body onload="setInterval('loadTime()', 200);">
因此在脚本中被覆盖:
window.onload = function()
{
stopwatch('Start');
}
这意味着永远不会执行原始onload
调用。
您应该尝试使用addEventListener
,以便为同一事件添加多个事件处理程序。
还有几点:
setInterval
和setTimeout
,只需传递函数本身即可。更高效,更不容易出错:setInterval(loadTime, 200);