初学js,不明白这代码为什么不起作用
为什么点了button之后,"xxx"的alter没有出来呢?请从原理上解释下呢?
我知道换成
<button id="myButton" onclick="myFunction()">This is a button</button>
就OK了,但是原理呢?
为什么
var bt = document.getElementById("myButton");
bt.onclick="myFunction()";
这种方式先获取到对象,然后设置onclick事件不行呢??
<head runat="server">
<link href="CSS/css%20style.css" rel="stylesheet" type="text/css" />
<title>Demo page</title>
<script type="text/javascript">
function myFunction()
{
alert("xxx");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button id="myButton" style="background-color:Blue">This is a button</button>
<script type="text/javascript">
var bt = document.getElementById("myButton");
bt.onclick="myFunction()";
</script>
</div>
</form>
</body>
</html>
------解决方案--------------------var bt = document.getElementById("myButton");
bt.onclick=myFunction;