首页 > 解决方案 > 关于在 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>

有人可以帮我解释为什么这也有效吗?

标签: javascripthtml

解决方案


setTimeout引用超时到期时应调用的函数,而不是字符串。

虽然setTimeout可以取一个字符串evald, 但不要使用它这与它一样存在安全风险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>


推荐阅读