You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模块模式导入变量后onclick函数报Uncaught ReferenceError问题解决

问题原因

使用type="module"时,JS文件会以ES模块模式运行,模块拥有独立的作用域,内部定义的函数getdata不会自动暴露到全局window对象中,因此HTML内联的onClick="getdata()"无法找到该函数,导致报错。

解决方法

方法1:手动将函数挂载到全局作用域

修改index.js,在函数定义后将其挂载到window对象:

import data from './app.js';
function getdata(){
 console.log("hello");
 console.log(data);
}
// 将函数暴露到全局
window.getdata = getdata;

这样HTML中的内联点击事件就能访问到getdata函数了。

方法2:使用事件监听替代内联事件(推荐)

这种方式更符合模块化开发规范,避免污染全局作用域:

  1. 修改index.html,给按钮添加ID并移除内联onClick属性:
<!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 id="getDataBtn">get data</button>
  <script type="module" src="./index.js"></script>
 </body>
</html>
  1. 修改index.js,通过DOM API绑定点击事件:
import data from './app.js';
function getdata(){
 console.log("hello");
 console.log(data);
}
// 获取按钮元素并绑定点击事件
document.getElementById('getDataBtn').addEventListener('click', getdata);

注意:无需在HTML中单独引入app.js,index.js已经通过import导入了它。

内容的提问来源于stack exchange,提问作者Shivam Batham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:33:33