从 HTML 中的 JavaScript 模块调用函数 [英] Call function from JavaScript module in HTML

查看:32
本文介绍了从 HTML 中的 JavaScript 模块调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,我有以下使用 Vue 的 JavaScript 模块:

Say, I have the following JavaScript module using Vue:

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>

然后我尝试调用changeMes​​sage:

<button onclick="changeMessage();">Press me</button>

但是,我在控制台中收到以下错误:

However, I get the following error in console:

未捕获的引用错误:在 HTMLButtonElement.onclick 中未定义 changeMes​​sage

Uncaught ReferenceError: changeMessage is not defined at HTMLButtonElement.onclick

此外,在 Visual Studio 中,我什至在 IntelliSense 中都没有得到它.当我删除 type="module" 时,一切正常.如何让html看到模块功能?

Moreover, in Visual Studio I don't even get it in IntelliSense. When I remove type="module", then everything works fine. How to make html see the module functions?

推荐答案

可以在全局window对象上定义函数:

You can define the function on the global window object:

<script type="module">

  window.greet = function () {
    alert('Hello')
  }

</script>

<button onclick="greet()">Hello</button>

这篇关于从 HTML 中的 JavaScript 模块调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆