关于使用JavaScript调用函数,哪一个是正确的?

时间:2018-07-11 09:56:41

标签: javascript html

我用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>

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

1 个答案:

答案 0 :(得分:1)

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>