问题描述
我在 html 中创建了一个动态表 click here to view image 行是在 javascript 中动态创建的,请参考图片 click here to view image 表的数据是从 firebase 中获取的。
我面临的问题是在表的末尾重复添加行,导致重复的行,请参考图片 click here to view image 如何使用 javascript 删除旧行并添加新的更新行。
解决方法
我已经用评论更新了 snapshot.forEach
循环。
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id',val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});