我从 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+"' />";
}
但问题是,每当我创建更多行时,我都需要使表按“名称”升序排列吗?可能吗?
最佳答案
当然可以。插入后:
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;
所以我们的想法是选择行,然后按输入名称属性对其进行排序。希望对您有所帮助。
关于javascript - 在表中添加更多行时使用js重新排序表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735702/