我在Visual Studio文件夹中具有以下HTML/CSS/JavaScript文件。我正在尝试将我的DIV元素用ID =" TOP"更改为"文本更改",而不是" TOP"。如您所见,它在代码段中正常运行,但是当我在Visual Studio中使用Live Server扩展程序运行HTML文件时,JavaScript无法更改。我相信我将我的CSS和JavaScript链接到我的HTML文件。这里怎么了?
document.getElementById("top").innerHTML = "Text change";
#top {
text-align: center;
color: green;
}
#middle {
text-align: center;
color: blue;
margin-top: 500px;
}
#bottom {
text-align: center;
color: red;
margin-top: 1000px;
}
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="javascript-test.js"></script>
<div id="top">top</div>
<div id="middle">middle</div>
<div id="bottom">bottom</div>
</body>
您的JavaScript在HTML加载之前正在运行。在关闭</body>
标签之前,将<script>
标签移至页面底部:
<script src="javascript-test.js"></script>
</body>
尝试将<script>
标签放在<head>
中,以使JavaScript首先运行。
<head>
<link rel="stylesheet" href="style.css">
<script src="javascript-test.js"></script>
</head>