在我的 HTML 文件中,我有一个 id="list"的 div。 现在我想在我的 html 中显示来 self 的 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 元素(即您想使用 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
)看起来像这样:
index.html
<!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>
列表.js
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;
}
关于javascript - 如何在 HTML 中显示字符串 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658421/