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

点击表格行按钮报data is not defined at HTMLButtonElement.GetADocument错误求解

问题排查与修复方案

根因说明

    1. GetADocument函数内直接调用的data是表格渲染阶段的局部变量,点击事件触发时该变量已无法访问,需要从点击的按钮上读取预先存储的data-id值
    1. 循环生成的按钮使用了重复的id="viewDetail",HTML中id必须唯一,导致只有第一个行的按钮能成功绑定点击事件
    1. 表单变量声明时boxName对应的id拼写错误,HTML中为nameBox,代码中错写为namaeBox,后续填充数据时会出现取值异常

修复代码

1. 调整点击事件函数,读取按钮的data-id

async function GetADocument(e){
    // 获取触发点击事件的按钮元素
    const clickBtn = e.currentTarget;
    // 读取按钮上存储的Firestore文档ID
    const docId = clickBtn.dataset.id;
    var ref = doc(firestore, "ordered", docId);
    const docSnap = await getDoc(ref)

    if(docSnap.exists()){
        boxEmail.value = docSnap.data().paidby;
        boxDate.value = docSnap.data().boughtAt;
        boxName.value = docSnap.data().cetegory;
        boxQty.value = docSnap.data().amount;
        boxAddress.value = docSnap.data().paidby;
        boxCode.value = docSnap.data().code;
        boxEstimation.value = docSnap.data().estimationDate;
        boxStatus.value = docSnap.data().status;
    }
    else{
        alert('No Document found')
    }
}

2. 调整表格行渲染逻辑,移除重复id、正确绑定事件

const q = query(collection(firestore, "ordered"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
  // 先清空旧表格内容,避免重复渲染
  document.getElementById("tbody1").innerHTML = '';
  querySnapshot.forEach((doc) => {
    let id = doc.id;
    let data = doc.data();

    const list = document.getElementById("tbody1");
    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)} (${(data.amount)})</td>
        <td class="grid-item">${(data.status)}</td>
        <td class="grid-item">
            <button type="button" class="btn btn-primary my-2 ml-2" data-id="${id}">View Details</button>
        </td>
        `;
    list.appendChild(row);
    // 从当前行内查询按钮绑定事件,无需依赖id
    const detailView = row.querySelector('button');
    detailView.addEventListener('click', GetADocument);
  });
});

3. 修正表单变量的id拼写错误

let boxEmail = document.getElementById('emailBox');
let boxDate = document.getElementById('dateBox');
// 修正拼写错误,将namaeBox改为nameBox
let boxName = document.getElementById('nameBox');
let boxQty = document.getElementById('qtyBox');
let boxAddress = document.getElementById('addressBox');
let boxCode = document.getElementById('codeBox');
let boxEstimation = document.getElementById('estimationBox');
let boxStatus = document.getElementById('statusBox');

内容的提问来源于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.25 03:15:11