我可以使用setInterval定期重写页面上的<span> </span>

时间:2011-03-02 14:51:07

标签: javascript innerhtml setinterval

我不知道任何javascript但是试图了解以下代码。

我获得了以下代码,可以根据时间向用户发送消息。

now = new Date();
if (now.getUTCHours() >= 12) {
    document.write('`<span id="NextorNot" style="color:red;">`It is too late to enter`</span>`');
}
else {
    document.write('`<span id="NextorNot" style="color:green;">`You can still enter`</span>`');
}

这个工作正常,但我想让它定期更新,对于长时间坐在页面上的任何人都会看到当前的信息。经过大量的阅读,我得到了这个但我无法看到我出错的地方。

now = new Date();  
if (now.getUTCHours() >= 12)   {  
    document.write('`<span id="NextorNot" style="color:red;">`It is too late to enter`</span>`');  
}  
else {  
    document.write('`<span id="NextorNot" style="color:green;">`You can still enter`</span>`');  
}  
setInterval(
   function() {  
      if (now.getUTCHours() >= 12) {  
        document.getElementById('NextorNot').style.color = 'red';  
        document.getElementById('NextorNot').innerHTML = 'It is too late to enter');  
      }  
      else {  
        document.getElementById('NextorNot').style.color = 'green';  
        document.getElementById('NextorNot').innerHTML = 'You can still enter');  
      }  
   },  
   5000
);  

有人可以帮忙吗?

5 个答案:

答案 0 :(得分:3)

您忘记在now回调中更改/设置setInterval

答案 1 :(得分:1)

您有两个语法错误。

document.getElementById('NextorNot').innerHTML = 'It is too late to enter');document.getElementById('NextorNot').innerHTML = 'You can still enter');最后会额外加)

应该是

document.getElementById('NextorNot').innerHTML = 'It is too late to enter';
document.getElementById('NextorNot').innerHTML = 'You can still enter';

答案 2 :(得分:0)

试试这个:jsFiddle

now = new Date();
if (now.getUTCHours() >= 12)
{
    document.write('<span id="NextorNot" style="color:red;">It is too late to enter</span>');
}
else
{
    document.write('<span id="NextorNot" style="color:green;">You can still enter</span>');
}

setInterval(
function ()
{
    now = new Date();
    //alert( now );
    if (now.getUTCHours() >= 12)
    {
        document.getElementById('NextorNot').style.color = 'red';
        document.getElementById('NextorNot').innerHTML = 'It is too late to enter';
    }
    else
    {
        document.getElementById('NextorNot').style.color = 'green';
        document.getElementById('NextorNot').innerHTML = 'You can still enter';
    }
},
5000 );​

答案 3 :(得分:0)

几乎就在那里。在if和else分支中的'你仍然可以输入'文本之后删除右括号“)”。其他一切似乎都有效。

答案 4 :(得分:0)

您有几个语法错误 - 更新跨度内容时关闭括号。将其更改为:

setInterval(  
function (){  
if (now.getUTCHours() >= 12)  
    {  
        document.getElementById('NextorNot').style.color = 'red';  
    document.getElementById('NextorNot').innerHTML = 'It is too late to enter';  
    }  
    else  
    {  
        document.getElementById('NextorNot').style.color = 'green';  
    document.getElementById('NextorNot').innerHTML = 'You can still enter';  
    }  
},  
5000 );