javascript - 关于在 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>
推荐阅读
- node.js - 运行nodejs程序时出错
- javascript - It seems onChange="myFunction()" is only calling my function once?
- angularjs - 垫表中行的 ElementRef
- python - 具有多个 one-hot 数组的 Keras 模型的输入形状
- php - 如何将 PayPal 表单集成到 wordpress 网站中?
- c++ - 将可变参数解析为函数指针
- java - 我应该如何重写此代码以使用访问令牌连接到 Netsuite?
- javascript - 分页显示 5 页并隐藏其余页面
- c++ - 为什么 std::filesystem::path::root_name() 返回空字符串?
- xamarin - Xamarin.Android 中的错误:“Emgu.CV.CvInvoke”的类型初始化程序引发异常