由於某種原因,我無法在JavaScript超時後更改HTML。下面是我使用的代碼:超時後無法更改HTML
setTimeout("$(\"#display p\").html(newDescription);", 250);
是不是有什麼問題呢?如果我刪除超時,腳本完美地工作。下面是該版本:
$("#display p").html(newDescription);
我運行Chrome 22,如果有什麼差別
由於某種原因,我無法在JavaScript超時後更改HTML。下面是我使用的代碼:超時後無法更改HTML
setTimeout("$(\"#display p\").html(newDescription);", 250);
是不是有什麼問題呢?如果我刪除超時,腳本完美地工作。下面是該版本:
$("#display p").html(newDescription);
我運行Chrome 22,如果有什麼差別
是第一個參數應該是功能。
var newDescription = 'The Description';
setTimeout(function(){
$("#display p").html(newDescription);
}, 250);
OR
var newDescription = 'The Description',
myfunc = function(){
$("#display p").html(newDescription);
};
setTimeout(myFunc, 250);
此外newDescription
必須在你的函數訪問的範圍。
將字符串傳遞給setTimeout時,代碼將在全球範圍中進行評估。 newDescription
很可能是本地變量,因此在250 ms超時後評估代碼時不可用。
您不應該將字符串傳遞給setTimeout(),出於同樣的原因,您不應該使用eval()。通過傳遞一個函數,您可以保留您的作用域變量,並且您可以獲得更好的性能,因爲JavaScript引擎可以優化您的函數(但無法優化字符串參數中的代碼)。
var newDescription = "My fancy new description";
setTimeout(function(){
$("#display p").html(newDescription);
}, 250);
另外,傳遞函數參數會創建一個閉包,存儲任何局部變量,以便即使在超時後也可以使用它們。:) –
@DavidMårtensson正確!即使在外部函數返回後,setTimeout回調函數也會使'newDescription'變量保持活動狀態,以便在定時器耗盡時訪問它。 –
但是,第一個參數也可以是一個字符串。 – VisioN
@VisioN但它不應該。 –
@Vision:是的,但一個可以解決的功能。 – prodigitalson