[英]How to retrieve document elements - Document ready
有人可以解释为什么这个按钮不起作用? 我的控制台中的错误表明var button = document.getElementById('next');
返回null
。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
...
</script>
</head>
<body>
<button id="next">Say hi</button>
</body>
</html>
使用Javascript:
var button = document.getElementById('next');
function sayHi(){
alert('Hi there');
}
button.addEventListener('click',sayHi,false);
谢谢你的帮助
加载HTML 后运行JS。 当您在头部调用JS时,该按钮尚不存在,它在调用JS后呈现。
这将有效:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="next">Say hi</button>
<script type="text/javascript">
...
</script>
</body>
</html>
在脚本运行时,您没有next
id的元素。
<script>
元素,使其出现在具有该id 或的元素之后 例如
function sayHi(){
alert('Hi there');
}
function setUpButton() {
var button = document.getElementById('next');
button.addEventListener('click',sayHi,false);
}
addEventListener('load', setUpButton);
您的脚本运行得太早,您的DOM(文档对象模型) 尚未就绪 。
如果您的<script>
位于文档的<head>
,请使用onreadystatechange
(现代浏览器):
<head>
里面 <script>
document.onreadystatechange = function () {
if(document.readyState === "interactive") { // use "complete" as a 'load' alternative
/* (DOM is now read and ready to be manipulated) your code here */
}
}
</script>
</head>
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/readystatechange
https://developer.mozilla.org/en/docs/web/api/document/readystate
</body>
如果您需要支持IE8 <在结束</body>
标记之前放置所有JS:
<!-- Your page elements before the script tag -->
<script>
/* (DOM is now read and ready to be manipulated) your code here */
</script>
</body>
您已将脚本定位为在文档完全呈现之前运行,因此无法找到该按钮。 在文档末尾运行脚本,即
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="next">Say hi</button>
<script>
...
</script>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.