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

script设为module类型时onclick绑定函数报ReferenceError未定义求解

问题根因

  • 你使用了type="module"的脚本,ES Module 拥有独立的私有作用域,模块内部定义的函数、变量默认不会挂载到全局window对象上,而HTML行内写的onclick事件只能调用全局作用域下的方法,因此会找不到deleted1函数。
  • 额外问题:你把deleted1函数定义在forEach循环内部,即使没有模块作用域的限制,该函数也是每次循环的局部函数,外部也无法访问。

解决方案

不要使用行内onclick绑定事件,改用JavaScript的事件绑定方式处理,具体修改如下:

第一步:补全导入依赖

你当前的导入语句缺少deleteDoc方法,先修改导入行:

import { getFirestore, doc, setDoc, collection, addDoc, getDocs, onSnapshot, query, where, orderBy, limit, deleteDoc } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-firestore.js";

第二步:修改行生成逻辑+绑定删除事件

把原来写onclick的部分去掉,改为创建元素后直接绑定事件:

const firestore = getFirestore();
// 把获取列表节点的逻辑提出来,不要放在循环里重复执行
const list = document.getElementById("tbody1");  
const querySnapshot = await getDocs(collection(firestore, "ordered"), orderBy("broughtAt"));
querySnapshot.forEach((doc) => {
    const id = doc.id
    const data = doc.data()
    const row = document.createElement("tr");
    row.innerHTML += `               
        <td class="grid-item">${data.paidby}</td>
        <td class="grid-item">No. ${data.numbur}, Simpang ${data.spg}, Jalan ${data.jln}, ${data.district}, ${data.code}</td>
        <td class="grid-item">'${data.product}'</td>
        <td class="grid-item">${data.amount}</td>
        <td class="grid-item">${data.status}</td>
        <td class="grid-item">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">Update Status</button>
            <!-- 去掉onclick,新增类名和data-id存储id -->
            <button type="button" class="btn btn-danger btn-primary my-2 ml-2 delete-btn" data-id="${id}">Delete</button>
        </td>
    `;
    // 给当前行的删除按钮绑定点击事件
    row.querySelector('.delete-btn').addEventListener('click', async () => {
        await deleteDoc(doc(firestore, "ordered", id));
        // 删除数据后同步移除页面上的行
        row.remove();
    })
    list.appendChild(row);
});

额外注意

你代码里的savePlant函数也是一样的问题,行内的onclick="savePlant()"也会报未定义错误,同样用事件绑定处理即可:

document.querySelector('#saveModeBtn').addEventListener('click', () => {
    // 把原来savePlant的逻辑写在这里
})

内容的提问来源于stack exchange,提问作者programming newbee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:36:02