[英]Which one is correct about calling a function in JavaScript?
I wrote a code in JavaScript shown below: in this code, onClick button wants to call function fadetext()
, and the function fadetext()
itself setTimeout. 我用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>
However, when I refer to the answer, the differences are shown in the following two lines of codes: 但是,当我参考答案时,以下两行代码显示了差异:
setTimeout("fadetext()",20);
Another one is: 另一个是:
<button onClick="fadetext()">Fade Text</button>
Could somebody helps me to explain why this also works? 有人可以帮我解释为什么这也行吗?
setTimeout
takes a reference to a function that should be called when the timeout expires, not a string. setTimeout
引用对超时到期时应调用的函数的引用,而不是字符串。
Although setTimeout
can take a string that is eval
d, do not use it , it's a security risk in the same way that eval()
is. 尽管setTimeout
可以接受eval
d的字符串, 但不要使用它 , 但与eval()
一样 , 它也存在安全风险。
setTimeout("fadetext()",20);
should be setTimeout(fadetext,20);
应该设置为setTimeout(fadetext,20);
and the onclick
attribute is all lowercase. 而onclick
属性全部为小写。
<button onClick="fadetext()">Fade Text</button>
should be <button onclick="fadetext()">Fade Text</button>
<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.