如何从另一个javascript文件调用类型为“=”的函数;模块";
如何从onclick或普通JavaScript调用模块JavaScript文件中的函数 在下面的代码中,单击按钮会引发“exampleFunction未定义”异常(使用最新的FireFox版本进行测试,并希望与现代浏览器兼容) exampleModule.js如何从另一个javascript文件调用类型为“=”的函数;模块";,javascript,Javascript,如何从onclick或普通JavaScript调用模块JavaScript文件中的函数 在下面的代码中,单击按钮会引发“exampleFunction未定义”异常(使用最新的FireFox版本进行测试,并希望与现代浏览器兼容) exampleModule.js export function exampleFunction(){ alert('example Function'); } examplePage.html <html> <head>
export function exampleFunction(){
alert('example Function');
}
examplePage.html
<html>
<head>
<script src="exampleModule.js" type="module"></script>
</head>
<body>
<button onclick="exampleFunction();">button</button>
</body>
</html>
按钮
您可以在模块内注册onclick处理程序
var element = (get your element with any document.<> Method)
element.addEventListener("click" (e) =>{ /*Your Handler Function */})
var-element=(使用任何document.Method获取元素)
addEventListener(“单击”(e)=>{/*您的处理程序函数*/})
您可以在模块内注册onclick处理程序
var element = (get your element with any document.<> Method)
element.addEventListener("click" (e) =>{ /*Your Handler Function */})
var-element=(使用任何document.Method获取元素)
addEventListener(“单击”(e)=>{/*您的处理程序函数*/})
尝试在全局上下文中使用此函数,请使用窗口
exampleModule.js
exampleFuction=function(){
alert('example Function');
}
export exampleFunction // export as a module
window.exampleFunction = exampleFunction; // export to the global context
尝试在全局上下文中使用此函数,请使用
window
exampleModule.js
exampleFuction=function(){
alert('example Function');
}
export exampleFunction // export as a module
window.exampleFunction = exampleFunction; // export to the global context
在使用之前,您需要将脚本导入到文件中。只需在此处导入函数我们有相同的问题,您需要将函数分配给全局对象(
window
),以便使用exampleFunction()从属性中选择代码>。您也可以使用addEventListener()
。您将在此处找到答案-->您需要在使用脚本之前将脚本导入文件。只需在此处导入函数我们有相同的问题,您需要将函数分配给全局对象(窗口
),以便您可以使用exampleFunction()从属性中选择代码>。您还可以使用addEventListener()
。您将在这里找到答案-->仅适用于填充全局变量空间的onclick,并且所有模块都是异步加载的,因此“exampleFunction”在用户尝试单击时未定义,因此只有像onclick这样的东西会出现错误,它填充了全局变量空间,并且所有模块都异步加载,因此可能会发生错误;在用户尝试单击时未定义“exampleFunction”,因此会出现错误