gpt4 book ai didi

javascript - 使用 body onload 和 document.write 时忽略样式表

转载 作者:数据小太阳 更新时间:2023-10-29 06:07:50 25 4
gpt4 key购买 nike

我正在用 JavaScript 进行实验以感受它,并且已经遇到了一个问题。这是我的 html 代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>

这是 JavaScript testing.js:

function writeLine()
{
document.write("Hello World!")
}

这是样式表styles.css:

html, body {
background-color: red;
}

这是一个非常简单的例子,但我可能选择了一个尴尬的例子,在 body 标签中使用 on-load。所以上面的代码加载并运行函数,但样式表什么都不做,除非我删除头部的脚本标签。我试过将脚本标签放在其他地方,但没有任何效果。我在网上研究了如何正确链接到 JavaScript 文件,但没有找到明确的解决方案,有人可以指出我的错误吗?

我以前用过 JavaScript,但我想从头开始清楚地了解它,然后再使用它

最佳答案

您不能在文档关闭后使用 document.write(当 onload 触发时)而不破坏现有文档(包括样式表的链接)。

相反,使用 DOM 操作,这在 W3C JavaScript Core Skills 的第 8 章和第 9 章中有所介绍。 .

关于javascript - 使用 body onload 和 document.write 时忽略样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10785519/

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