您面临的问题是由于 ES 模块处理脚本文件的方式造成的。在 ES 模块中,每个文件都被视为具有自己作用域的单独模块,这意味着一个模块中定义的函数和变量在另一个模块中无法访问,除非显式导出和导入。
要解决此问题,您可以按照以下方式修改代码:
在index.html中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>click me</button>
<div></div>
<script type="module" src="script.mjs"></script>
</body>
</html>
在 script.mjs 中
function welcomeMessage() {
console.log("Hello World!");
}
const buttonUser = document.querySelector("button");
const divUser = document.querySelector("div");
buttonUser.addEventListener("click", () => {
divUser.innerHTML = `
<h1> welcome to the page </h1>
<button onclick="welcomeMessage()"> click me 2 </button>
`;
});