gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:23:25 25 4
gpt4 key购买 nike

有人可以解释为什么这个按钮不起作用吗?我的控制台中的错误表明 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>

关于javascript - 如何检索文档元素 - 文档就绪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com