簡體   English   中英

關於使用JavaScript調用函數,哪一個是正確的?

[英]Which one is correct about calling a function in JavaScript?

我用JavaScript編寫了一個代碼,如下所示:在此代碼中,onClick按鈕要調用函數fadetext() ,而函數fadetext()本身就是setTimeout。

 hex = 255 // Initial color value. function fadetext() { if (hex > 0) { //If color is not black yet hex -= 11; // increase color darkness document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")"; setTimeout(fadetext, 20); } else hex = 255 //reset hex value } 
 <div id="sample" style="width:100%"> <h3>John slowly faded into view</h3> </div> <button onClick=fadetext()>Fade Text</button> 

但是,當我參考答案時,以下兩行代碼顯示了差異:

setTimeout("fadetext()",20);

另一個是:

<button onClick="fadetext()">Fade Text</button>

有人可以幫我解釋為什么這也行嗎?

setTimeout引用對超時到期時應調用的函數的引用,而不是字符串。

盡管setTimeout可以接受eval d的字符串, 但不要使用它但與eval()一樣它也存在安全風險。

setTimeout("fadetext()",20); 應該設置為setTimeout(fadetext,20);

onclick屬性全部為小寫。

<button onClick="fadetext()">Fade Text</button>應為<button onclick="fadetext()">Fade Text</button>

 var hex = 255 // Initial color value. function fadetext() { if (hex > 0) { //If color is not black yet hex -= 11; // increase color darkness document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")"; setTimeout(fadetext, 20); } else hex = 255 //reset hex value } 
 <div id="sample" style="width:100%"> <h3>John slowly faded into view</h3> </div> <button onclick="fadetext()">Fade Text</button> 

暫無
暫無

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

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