在我的HTML文件中,我有一个id =“list”的div。现在我想在我的html中显示我的javascript中的字符串。页。但是没有发生。在我的html文件中,我导入了srcipt文件。以下是我在脚本文件中的外观:
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
你需要在你的dom之后放置JavaScript代码,并用Script标签包装。
示例:这将起作用,因为我们首先渲染HTML然后将js执行到其中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will WorK</title>
</head>
<body>
<div id="list" ></div>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
</body>
</html>
但是这不起作用,因为在dom渲染之前执行JavaScript。此外,这可能会引发错误Cannot set property 'innerHTML' of null"
,因为getElementById将无法找到相关的dom。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This Will Not WorK</title>
</head>
<body>
<script>
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
</script>
<div id="list" ></div>
</body>
</html>
把你的代码放在这里,它会工作
window.onload = function(){}
每当你定位DOM元素(即你想使用document.getElementById("my-element")
或类似的东西)时,你需要首先检查文档是否已加载。
您可以通过以下任一方式执行此操作:
window.onload = function(){
//Now that the window has loaded we can target DOM elements here
}
要么
document.addEventListener('DOMContentLoaded', function () {
//Now that the contents of the DOM have loaded we can target DOM elements here
});
所以一个完整的例子(将你的脚本代码放在外部文件,即list.js
)看起来像这样:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8">
<title>My list website</title>
<script src="list.js"></script>
</head>
<body>
<div id="list"></div>
</body>
</html>
window.onload = function(){
//We use window.onload to check the window has loaded so we can target DOM elements
var namesArray = ["lars", "bo", "ib", "peter", "jan", "frederik"];
var list = namesArray.map(name=>"<li>"+name+"</li>");
var listAsStr ="<ul>" + list.join("") + "<ul>";
document.getElementById("list").innerHTML = listAsStr;
}
这是使用模板字符串完成它的简洁方法。只需将所有内容包装到您分配给window.onload
的函数中:
<script>
window.onload = () => {
const namesArray = ['lars', 'bo', 'ib', 'peter', 'jan', 'frederik'];
const list = `<ul>${namesArray.map(name => `<li>${name}</li>`).join('')}</ul>`;
document.getElementById('list').innerHTML = list;
};
</script>
<div id="list"></div>