在JavaScript中调用函数的两种不同方式

时间:2014-10-24 15:11:18

标签: javascript html

在下面的代码中,一旦我运行它,它会等待click事件触发警报。但是,如果我更改以下javascript代码

  

clickMeButton.onclick = runTheExample;

  

clickMeButton.onclick = runTheExample();

在没有任何点击事件的情况下下载页面时,它始终会发出警报。我想知道有什么区别。我正在使用Chrome。剪切代码如下:

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
    <script type="text/javascript" src="script13.js">   </script>
</head>

<body>
    <h1 id="title">DOM Example </h1>
    <p id="first">This is the first paragraph</p>
    <p id="second"><strong>This is the second paragraph</strong></p>
    <p id="third">This is the third paragraph</p>
    <input type ="text" id="myTextBox" />
    <input type ="submit" id="clickMe" value="Click Me!"/>
    <a href="http://www.google.com" id="MyGoogle"> Google! </a>
</body>
</html>

//script13.js
window.onload= function(){
var clickMeButton=document.getElementById('clickMe');
clickMeButton.onclick=runTheExample;
}

function runTheExample(){
alert('running the example');
}

1 个答案:

答案 0 :(得分:3)

var x = func(); //Means you execute the function and output its return value to x;

var x = func; //Means you attribute the function to the variable, so you can call it, using x.

实施例

function f(){
 return 4;
}

var x = f(); // x = 4
var x = f; // x = f()