document.getElementById("myButton2").onclick = buttonAlert; 放的位置问什么会对代码执行效果有影响
<html>
<head>
<title>onclick</title>
<script type="text/javascript">
function buttonAlert(){
alert("you clicked the button");
//document.getElementById("myButton2").onclick = buttonAlert;
//为什么把这句放外面就无效了,放在这里有效
}
document.getElementById("myButton2").onclick = buttonAlert;
//函数名后不能有括号,否则,就先执行buttonAlert()函数并赋值给onClick
</script>
</head>
<body>
<input type="button" id="myButton1" value="myButton1" onClick="buttonAlert()" />
<input type="button" id="myButton2" value="myButton2" />
</body>
</html>