javascript – 在表中添加更多行时使用js重新排序表

我从JS创建一个表来添加更多行

function addItem(code,name) {  
    var tblList = document.getElementById("list_inventory");
    var tblBody = tblList.tBodies[0];
    var lastRow = tblBody.rows.length;
    var row     = tblBody.insertRow(lastRow);               

    var newCell = row.insertCell(0);
    newCell.innerHTML = lastRow+1;

    var newCell = row.insertCell(1);
    newCell.innerHTML = name+"<input type='hidden' name='code[]' id='code[]' value='"+code+"' />";
}

但问题是,每当我创建更多行时,我需要通过’name’来提升表格吗?可能吗?

最佳答案 当然有可能.插入后:

var rows = tblBody.rows;
rows.sort(function(a,b) {
    var first = a.cells[0].children[0].name;
    var second = b.cells[0].children[0].name;
    return (first.name < second.name) ? 1 : ((first.name > second.name) ? -1 : 0);
});
tblBody.rows.innerHTML = rows;

所以我的想法是选择行,然后按输入名称prop对其进行排序.希望它能帮到你.

点赞