簡體   English   中英

setInterval在Firefox中無法正常工作

[英]setInterval doesn't work correctly in firefox

我對我的網站無限循環使用setInterval函數,但是Firefox僅處理第一個間隔,而對於下一個間隔,Firefox的我的收藏夾圖標變為加載,並且F5和“刷新”按鈕不起作用。

function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    document.write(hours + ":" + mins + ":" + sec);
}

setInterval("printTime()", 1000);

這是完全可以預期的。 在初始加載頁面時不要分開使用document.write

創建一個元素並將其附加到主體。

例如 :

function printTime(){
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    var txt = document.createTextNode(hours + ":" + mins + ":" + sec);
    document.body.appendChild(txt); 
}
setInterval(printTime, 1000); // note also the difference here : don't eval

請注意,幾個小時后,您的頁面會有點長。 如果您想更改元素而不是附加元素,則可以

document.getElementById('someId').innerHTML = hours + ":" + mins + ":" + sec; 

刪除document.write 嘗試這樣的事情

$(document).ready(function () {
    function printTime() {
        var now = new Date();
        var hours = now.getHours();
        var mins = now.getMinutes();
        var sec = now.getSeconds();
        $("#myDiv").html(hours + ":" + mins + ":" + sec);
    }

    setInterval(printTime, 1000);
});
<div id="myDiv"></div>
<div id="test">Hello</div>

在文檔中添加以上html並運行此腳本

var flag = false;
function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
//    document.write(hours + ":" + mins + ":" + sec);
 if(flag==true)
 {
    document.getElementById("test").backgroundColor="green";
    flag = false;
 }else
 {
    document.getElementById("test").backgroundColor="red";
    flag = true;
 }

}

setInterval("printTime()", 1000);

如果它不起作用,那么巴林Firefox :)雖然可以肯定

試試這個簡單的例子:

function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    var div = document.getElementById('divID').innerHTML = hours + ":" + mins + ":" + sec;

}

setInterval(printTime(), 1000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM