![](/img/trans.png)
[英]How can I call a function from javascript module in html onclick
[英]Call function from JavaScript module in HTML
说,我有以下使用 Vue 的 JavaScript 模块:
import Vue from "./vue/vue.esm.browser.js";
const app = new Vue({
el: '#app',
data: {
message: 'Hello, world!',
}
});
// Custom function for calling by the button
function changeMessage() {
app.message = 'Hello from button!';
}
现在我指的是这个模块:
<script src="js/site.js" type="module"></script>
然后我尝试调用changeMessage
:
<button onclick="changeMessage();">Press me</button>
但是,我在控制台中收到以下错误:
未捕获的 ReferenceError:在 HTMLButtonElement.onclick 中未定义 changeMessage
此外,在 Visual Studio 中,我什至在 IntelliSense 中都没有。 当我删除type="module"
时,一切正常。 如何让html看到模块功能?
您可以在全局window
object 上定义 function:
<script type="module"> window.greet = function () { alert('Hello') } </script> <button onclick="greet()">Hello</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.