如何使用javascript用新行替换旧表行

问题描述

我在 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;
    }
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...