gpt4 book ai didi

JavaScript-当我的脚本在头时无法更改样式

转载 作者:搜寻专家 更新时间:2023-10-31 21:54:04 25 4
gpt4 key购买 nike

当我将脚本插入 headbody 元素时,我试图让我的 JavaScript 工作。

这是我的例子:


首先,我将它插入到 body 中,如 this example (工作):

    <html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>


当我将 script 移动到 body 的末尾时(也有效):

<html>
<body>

<p id="p2">Hello World!</p>

<p>The paragraph above was changed by a script.</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>


但是当我将它移到 head 时,它停止工作:

	<html>
<head>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</head>
<body>

<p id="p2">Hello World!</p>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

最佳答案

使用关键字 defer为此:

延迟说明:

A script that will not run until after the page has loaded.

    <html>
<body>

<p id="p2">Hello World!</p>

<script defer>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

关于JavaScript-当我的脚本在头时无法更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45366882/

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