从外部文件导入对象数组遇ts(6133)错误:toggle函数未被读取
解决模块化拆分后toggle函数未被识别及TS未使用提示问题
你遇到的问题核心是ES模块的作用域隔离:当脚本被设为type="module"后,logic.js里的toggle函数属于模块局部作用域,HTML内联的onclick="toggle(${i})"是在全局作用域查找函数,自然找不到;同时TypeScript因检测不到函数被调用,抛出了“已声明但未被读取”的提示。此前单文件未用模块时,函数处于全局作用域,所以能正常运行。
下面提供两种解决方法:
方案1:使用事件委托(推荐)
这种方式无需内联事件,符合现代前端规范,同时彻底解决作用域问题:
修改logic.js代码如下:
import { examples } from "./Předměty/Matematika.js"; // 调整toggle逻辑,接收点击的按钮元素作为参数 function toggle(buttonEl) { // 直接通过按钮的兄弟节点找到对应的结果容器 const resultDiv = buttonEl.nextElementSibling; resultDiv.style.display = resultDiv.style.display !== "none" ? "none" : "block"; } let html = ""; examples.forEach((ex, i) => { const example = ` <div class="card"> <div class="example"> ${ex.question} </div> <button type="button" class="toggle"> Toggle </button> <div id="result_${i}" style="display:none" class="result">${ex.answer}</div> </div>`; html += example; }); const container = document.querySelector("#examples-container"); container.innerHTML = html; // 给容器添加事件委托,统一处理按钮点击 container.addEventListener("click", (e) => { if (e.target.classList.contains("toggle")) { toggle(e.target); } });
方案2:将toggle挂载到全局作用域(快速修复,不推荐)
如果只是临时应急,可以把函数挂到window对象上,让全局作用域能访问到:
修改logic.js中的toggle函数定义:
// 将函数挂载到全局window对象 window.toggle = function(i) { const div = document.querySelector(`#result_${i}`); div.style.display = div.style.display !== "none" ? "none" : "block"; };
这种方法能快速让内联onclick找到函数,同时消除TS的未使用提示,但会污染全局作用域,不适合复杂项目。
内容的提问来源于stack exchange,提问作者user20838375
相关产品推荐
相关产品推荐

