【发布时间】:2019-09-17 22:20:24
【问题描述】:
当我将模块直接添加到 html 代码中时,我的代码工作正常,但是当我尝试首先将模块导入到不同的 javascript 文件时,它不会加载它。
我已经尝试从我的模块中导出所有内容。
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
它应该向 div 添加元素。但除非我直接使用sidebarmodule.js,否则它不会这样做。我想通过app.js来做
编辑
找到问题了!
没有在 for 循环中初始化索引。
EDIT2
还有需要添加的type="module"
【问题讨论】:
-
导入是异步的。 sidebarmodule.js 在您尝试调用它时不会被加载。阅读the documentation on import 了解如何使用
.then() -
好的,谢谢大家的帮助。问题仍然存在。我按照 Archer 的建议更改了代码,但它仍然不会更改 html。 app.js 当前: import("./visualModules/sidebarmodule") .then((sidebar) => { sidebar.createSidebar(); });我还将 type="module" 添加到脚本标签,但它也没有帮助。我还尝试将脚本标签放入标题中,添加异步/延迟,但这些都不起作用。
标签: javascript html ecmascript-6