Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检索文档元素-文档就绪_Javascript - Fatal编程技术网

Javascript 如何检索文档元素-文档就绪

Javascript 如何检索文档元素-文档就绪,javascript,Javascript,有人能解释一下为什么这个按钮不起作用吗?我的控制台中的错误表明var button=document.getElementById('next')正在返回null HTML: 感谢您的帮助在加载HTML后运行JS。当您在头部调用JS时,按钮还不存在,它在调用JS后呈现 这将有助于: <!DOCTYPE html> <html lang="en"> <head> </head> <body> <button id="nex

有人能解释一下为什么这个按钮不起作用吗?我的控制台中的错误表明
var button=document.getElementById('next')正在返回
null

HTML:


感谢您的帮助

在加载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>

打招呼
...
在脚本运行时,您没有id为
next
的元素

  • 移动
    元素,使其显示在具有该id或
  • 将脚本内容包装到函数中,并将该函数绑定为将在元素存在后运行的事件的事件处理程序
e、 g


脚本运行太早,并且DOM(文档对象模型)尚未就绪 如果您的
位于文档的
内,请使用
onreadystatechange
(现代浏览器):

DOM就绪-内部

document.onreadystatechange=函数(){
如果(document.readyState==“interactive”){//使用“complete”作为“load”选项
/*(DOM现在已被读取并准备好进行操作)这里是您的代码*/
}
}​


DOM就绪-关闭前
如果您需要支持IE8<将所有JS放在关闭标记之前<代码>

<!-- Your page elements before the script tag -->

<script>
   /* (DOM is now read and ready to be manipulated) your code here */
</script>
</body>

/*(DOM现在已被读取并准备好进行操作)这里是您的代码*/

您已将脚本定位为在文档完全呈现之前运行,因此无法找到按钮。 在文档末尾运行脚本,即

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="next">Say hi</button>
<script>
    ...
</script>
</body>

打招呼
...

readystatechange事件可能会触发多次。如果不测试该文档,可能就不应该使用它。readyState==“complete”。
function sayHi(){
    alert('Hi there');
}

function setUpButton() {
    var button = document.getElementById('next');
    button.addEventListener('click',sayHi,false);
}

addEventListener('load', setUpButton);
<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>
<!-- 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>