在 table 中按字母顺序插入 table 行
Insert a table row alphabetically ordered in the table
我有一个 table 按名称字母顺序排列(使用 PHP mysql),现在我想在 [=] 的正确位置插入一个新行17=] 没有向服务器发出新的请求。有没有办法通过 table 检查每个名称并使用 jQuery/Javascript 在正确的位置插入新行?
有很多方法,这只是其中一种方法 jquery:
让我们设置您的新名称和新行 el
var newName = 'YourNewName'
var newRow = $('<tr>') // created new row element with cells
获取名称列表,添加新名称并对它们进行排序;假设您的姓名列是 2
var names = $('td:nth-child(2)').map(function () {return $(this).text()})
names.push(newName)
var sorted = names.sort()
获取添加名称的位置
var newNamePos = sorted.indexOf(newName)
正在将新行插入找到的位置
$('tr:nth-child(' + (newNamePos + 1) + ')').before(newRow)
您也可以将其插入末尾(或任何位置),然后使用 js/jquery:
对整个 table 重新排序
var table = $('table'),
rows = $('tr', table);
$('#sortIt').click(function () {
rows.sort(function(a, b) {
var keyA = $('td',a).text();
var keyB = $('td',b).text();
return (keyA > keyB) ? 1 : 0;
});
rows.each(function(index, row) {
table.append(row);
});
});
我有一个 table 按名称字母顺序排列(使用 PHP mysql),现在我想在 [=] 的正确位置插入一个新行17=] 没有向服务器发出新的请求。有没有办法通过 table 检查每个名称并使用 jQuery/Javascript 在正确的位置插入新行?
有很多方法,这只是其中一种方法 jquery:
让我们设置您的新名称和新行 el
var newName = 'YourNewName'
var newRow = $('<tr>') // created new row element with cells
获取名称列表,添加新名称并对它们进行排序;假设您的姓名列是 2
var names = $('td:nth-child(2)').map(function () {return $(this).text()})
names.push(newName)
var sorted = names.sort()
获取添加名称的位置
var newNamePos = sorted.indexOf(newName)
正在将新行插入找到的位置
$('tr:nth-child(' + (newNamePos + 1) + ')').before(newRow)
您也可以将其插入末尾(或任何位置),然后使用 js/jquery:
对整个 table 重新排序var table = $('table'),
rows = $('tr', table);
$('#sortIt').click(function () {
rows.sort(function(a, b) {
var keyA = $('td',a).text();
var keyB = $('td',b).text();
return (keyA > keyB) ? 1 : 0;
});
rows.each(function(index, row) {
table.append(row);
});
});