点击表格行按钮报data is not defined at HTMLButtonElement.GetADocument错误求解
问题排查与修复方案
根因说明
GetADocument函数内直接调用的data是表格渲染阶段的局部变量,点击事件触发时该变量已无法访问,需要从点击的按钮上读取预先存储的data-id值
- 循环生成的按钮使用了重复的
id="viewDetail",HTML中id必须唯一,导致只有第一个行的按钮能成功绑定点击事件
- 循环生成的按钮使用了重复的
- 表单变量声明时
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
相关产品推荐
相关产品推荐

