日期:2014-05-16  浏览次数:20347 次

一段简短的代码,为什么点击按钮没反应?
本帖最后由 q631263135 于 2013-03-28 10:45:27 编辑
<html><head>
<script>
document.getElementById("btn").onclick = function() {displayTime()};
function displayTime() {
document.getElementById("p").innerHTML = Date();
}
</script>
</head>

<body>
<p id="p">If you click the button,I will show the date.</p>
<button type="button" id="btn">show date</button>
</body>
</html>


------解决方案--------------------
因为你的JS执行的时候页面元素还没加载到。

要是你打开了控制台应该可以看到错误。

function displayTime() {
   document.getElementById("p").innerHTML = Date();
}
window.onload = function(){
    document.getElementById("btn").onclick = function() {displayTime()};
}

JS部分改成这样
------解决方案--------------------
把script移到<button type="button" id="btn">show date</button>后面。