<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>后面。