动态添加和删除 HTML 表中的行

Dynamically add and remove rows in an HTML table

本文关键字:HTML 添加 删除 动态      更新时间:2023-09-26

我创建了一个下拉列表,在添加新行时从下拉列表中选择某些内容时,该表应删除现有行。

我可以添加,但我不知道如何删除旧的。帮助!

var currencies;
$.ajax({
    url: 'data.json',
    type: "post",
    dataType: "json",
    method: "GET",
    success: function (data, textStatus, jqXHR) {
        currencies = data[0].currencies; 
        drawTable(currencies);
    }
});

function drawTable(currencies) {
    for (var i = 0; i < currencies.length; i++) {
        drawRow(currencies[i]);
    }
}

function IfTheyPicked5Days() {
    if ($("#dropdown")[0].value=="fivedays") {
        return true;
    }
    else {
        return false;
    }  
}
function redrawTableForPeopleWhoPicked1Month() {
    drawTable(currencies);
}
function drawRow(rowData) {
var row = $("<tr />")
$("#currencyhomework").append(row);
row.append($("<td>" + rowData.currency + "</td>"));
row.append($("<td>" + rowData.country + "</td>"));
row.append($("<td>" + rowData.ranges.oneday + "</td>"));
if (IfTheyPicked5Days()){
    row.append($("<td>" + rowData.ranges.fivedays + "</td>"));
} else {
    row.append($("<td>" + rowData.ranges.onemonth + "</td>"));
}

}

        function drawTable(currencies) {
            //empty the table here:
             $("#currencyhomework").empty();
            for (var i = 0; i < currencies.length; i++) {
                drawRow(currencies[i]);
            }
        }

每次调用drawTable时,您都应该清空它。这样,表的每次(重新)绘制都从更新的数据开始。 Empty() 相当于 jQuery 的 element.innerHTML = null