Javascript 为什么随机出现一个错误,说Uncaught DOMException:Failed to execute';查询选择器';在';元素';:'';不是有效的选择器
我创建了一个expense tracker应用程序,我将用户的费用记录按日期、标题、金额存储在一个表中,并在“x”按钮的空白列中删除该行的费用文档。当用户单击“x”按钮时,它将从firestore中删除文档并从行中删除其数据 有时,单击“x”按钮时,文档会从firestore中删除,但不会从表中删除,除非刷新页面,页面基本上是从firestore中删除文档后重新读取费用文档Javascript 为什么随机出现一个错误,说Uncaught DOMException:Failed to execute';查询选择器';在';元素';:'';不是有效的选择器,javascript,firebase,google-cloud-firestore,css-selectors,Javascript,Firebase,Google Cloud Firestore,Css Selectors,我创建了一个expense tracker应用程序,我将用户的费用记录按日期、标题、金额存储在一个表中,并在“x”按钮的空白列中删除该行的费用文档。当用户单击“x”按钮时,它将从firestore中删除文档并从行中删除其数据 有时,单击“x”按钮时,文档会从firestore中删除,但不会从表中删除,除非刷新页面,页面基本上是从firestore中删除文档后重新读取费用文档 app.js:189 Uncaught DOMException: Failed to execute 'querySel
app.js:189 Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '[data-id=6yl9aPRGzLn1FCbXecfI]' is not a valid selector.
默认情况下,Firestore生成的文档ID可以包含字母和数字。当ID以数字开头时,这会导致属性选择器失败,因为属性值周围没有引号,属性值将被视为CSS
标记,不能以数字开头。这就是为什么您只能偶尔看到选择器失败的原因
在属性值周围添加引号将确保解析器不会根据文档ID的性质对其进行不同的处理:
let li=table.querySelector(“[data id=“”+change.doc.id+”);
/* CURRENT MONTH'S EXPENSE TABLE */
const table = document.querySelector('#record');
function expenseRecord(user) {
const docRef = db.collection('users').doc(user.uid).collection(`${year}-${month}`).orderBy('date', 'desc').limit(20);
docRef.onSnapshot((snapshot) => {
let changes = snapshot.docChanges();
changes.forEach((change) => {
if (change.type == 'added') {
let tr = document.createElement('tr');
let date = document.createElement('td');
let title = document.createElement('td');
let amount = document.createElement('td');
let cross = document.createElement('td');
tr.setAttribute('data-id', change.doc.id);
cross.setAttribute('class', 'btnDelete');
date.textContent = change.doc.data().date;
title.textContent = change.doc.data().title;
amount.textContent = `$${change.doc.data().amount}`;
cross.textContent = 'x';
tr.appendChild(date);
tr.appendChild(title);
tr.appendChild(amount);
tr.appendChild(cross);
table.appendChild(tr);
cross.addEventListener('click', (e) => {
e.stopPropagation();
let id = e.target.parentElement.getAttribute('data-id');
db.collection('users').doc(user.uid).collection(`${year}-${month}`).doc(id).delete();
});
} else if (change.type == 'removed') {
let li = table.querySelector('[data-id=' + change.doc.id + ']');
table.removeChild(li);
}
});
});
}
<table id="record">
<tr>
<th>Date</th>
<th>Title</th>
<th>Amount</th>
<th></th>
</tr>
</table>
let li = table.querySelector('[data-id=' + change.doc.id + ']');