我很难使用javascript模块..。
我有一个html文件和一个JS模块。我在javascript文件中定义了一个函数,我想从我的HTML页面调用该函数。这是我的密码
index.html
<html>
<head>
<script type="module" src="app.js"></script>
</head>
<body>
<button onclick="greetFromHtml();">greetFromHtml</button>
<button onclick="greetFromModule()"> greetFromModule</button>
<script type="text/javascript">
function greetFromHtml(){
alert('Hello');
}
</script>
</body>
</html>app.js
function greet(){
alert('Hello');
}greetFromHtml按钮工作正常。当我单击greetFromModule按钮时,会得到以下错误:hello is not defined at HTMLButtonElement.onclick
如果我将type="module"从标头中删除,那么所有这些都能正常工作,但是由于其他原因,我需要使用模块,所以这不是一个很好的解决方案。
我见过几个帖子说我需要导入/导出或使用窗口,但我不知道该怎么做。有人能给我一个答案吗?理想情况下,实现这一目标的最简单方法
见下文对我所审查的一些问题的提及:
function in my javascript module is not defined
Call functions in a JavaScript from an HTML
How to use code from script with type=module [duplicate]
ES6 Modules: Undefined onclick function after import
编辑我尝试了以下操作,但仍然得到相同的错误



编辑2答案中的代码正在工作。我只是想在本地运行,但我知道您需要一台服务器,所以如果您看到相同的错误,请将站点上传到服务器或使用本地服务器。
发布于 2021-11-08 19:20:25
首先,必须显式导出函数:
export function greet() {
alert("Hello from module");
}其次,模块有自己的作用域(这是模块的全部功能),因此需要将函数添加到全局范围。因此,要做到这一点,您必须运行一个导入函数并将其添加到window对象的脚本:
<script type="module">
import { greet } from "./app.js";
window.greetFromModule = greet;
</script>现在你不需要这个部分了<script type="module" src="app.js"></script>
或者,您可以创建一个空的obj并向其添加模块内容,如下所示:
<html>
<head></head>
<body>
<button onclick="greetFromHtml();">greetFromHtml</button>
<button onclick="module.greet()">greetFromModule</button>
<script type="text/javascript">
function greetFromHtml() {
alert("Hello");
}
const module = {};
</script>
<script type="module">
import { greet } from "./app.js";
module.greet = greet;
</script>
</body>
</html>发布于 2022-10-05 18:56:54
myscript.js
export const sampleFunction=()=>{
alert("Hello I'm sample");
}index.js
import {sampleFunction} from './myscript.js';
window.sampleFunction=sampleFunction;index.html
<script type='module' scr='./index.js'></script>
<button onclick="sampleFunction()">Click me</button>在script标记中,让脚本类型= 'module‘和src = './index.js’。现在它应该起作用了)
https://stackoverflow.com/questions/69888029
复制相似问题