為什么DOM0把script移到head里面后, 不彈框了
<title>無標題文檔</title>
<script>
var btn=document.getElementById("btn");
btn.onclick=function() { alert("no");}
</script>
</head>
<body>
<input type="button" value="按鈕" id="btn">
</body>
</html>
為什么DOM0把script移到head里面后, 不彈框了? ?非要移到body里面才可以
<input type="button" value="按鈕" id="btn" onclick="showmes()">
再在script里面封裝一個函數(shù), 也是用alert, 放head上面, 又可以顯示
2016-10-25
懂了,因為在加載<script> 的時候,btn還沒有在html中創(chuàng)建, 所以抓取不到,?
需要寫成這樣, 在網(wǎng)頁加載完成以后, 再重新加載一次onload的程序
<script type="text/javascript" >
window.onload = function () {
var btn=document.getElementById("btn");
btn.onclick=function () {
alert("OK");
}
}
</script>
2016-10-11
<title>無標題文檔</title>
</head>
<body>
<input type="button" value="按鈕" id="btn">
<script>
var btn=document.getElementById("btn");
btn.onclick=function() { alert("no");}
</script>
</body>
或者
<script>
function showmes() { alert("no");}
</script>
<title>無標題文檔</title>
</head>
<body>
<input type="button" value="按鈕" id="btn" onclick="showmes()">
</script>
</body>
上面這兩個都能正常跳出彈框