gpt4 book ai didi

javascript - getElementbyID,有人可以告诉我为什么这不起作用吗?

转载 作者:行者123 更新时间:2023-11-28 11:24:55 25 4
gpt4 key购买 nike

我正在尝试学习 JavaScript..并且我正在尝试遵循示例..并且我无法让这个 getElementById 正常工作...为什么它在警报框中显示 Null 而不是实际的段落?

<html>
<head>
<script type="text/javascript">
var x = document.getElementById('excitingText');
alert(x);
</script>
</head>

<body>
<h1>This is a header!</h1>
<p id="excitingText">
This is a paragraph! <em>Excitement</em>!
</p>
<p>
This is also a paragraph, but it is not nearly as exciting as the last one.
</p>

</body>

</html>

最佳答案

当你执行

var x = document.getElementById('excitingText');
alert(x);

页面尚未加载完毕。将其放在 window.onload 内或将其放在页面末尾即可使其正常工作。尝试:

window.onload = function() {
var x = document.getElementById('excitingText');
alert(x);
}

或者放在最后。但最好将其放在 window.onload 内。

<html>
<head>

</head>

<body>
<h1>This is a header!</h1>
<p id="excitingText">
This is a paragraph! <em>Excitement</em>!
</p>
<p>
This is also a paragraph, but it is not nearly as exciting as the last one.
</p>
<script type="text/javascript">
var x = document.getElementById('excitingText');
alert(x);
</script>
</body>

</html>

关于javascript - getElementbyID,有人可以告诉我为什么这不起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17288806/

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