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

时间:2015-01-09 18:38:36

标签: javascript jquery

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

我可以添加,但我无法弄清楚如何删除旧的。救命啊!

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>"));
}

}

1 个答案:

答案 0 :(得分:1)

        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