gpt4 book ai didi

javascript - 如何在 html 表格的特定位置插入 ?

转载 作者:行者123 更新时间:2023-11-30 06:22:18 24 4
gpt4 key购买 nike

我设计了一个带有标题的表格。我正在附加动态行 <tr>到这张 table 。追加时我丢失了行的顺序。关于如何解决此问题的任何建议或想法?提前致谢。

<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
-- dynamic rows will come.
</table>

var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.

$('#myTable').append(html1);
$('#myTable').append(html2);
$('#myTable').append(html3);

期望的输出:

<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
<tr id="1">
<td>aaa</td>
<td>aaa</td>
</tr>
<tr id="2">
<td>ccc</td>
<td>ccc</td>
</tr>
<tr id="3">
<td>bbb</td>
<td>bbb</td>
</tr>
</table>

最佳答案

这个你会做的。添加排序函数,然后按照以下链接中的说明调用该函数。

添加了基于 Jquery 内容排序链接的片段:- https://www.shift8web.ca/2017/01/use-jquery-sort-reorganize-content/

var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.

$('#myTable').append(html1);
$('#myTable').append(html2);
$('#myTable').append(html3);

var i;
var htmlcontent = $('#myTable').html();
$('#myTableOriginalContent ').html( $('#myTable').html())
sortMeBy('id', 'myTable', 'tr', 'asc')
function sortMeBy(arg, sel, elem, order) {
var $selector = $('#'+sel),
$element = $selector.children(elem);
$element.sort(function(a, b) {
var an = parseInt(a.getAttribute(arg)),
bn = parseInt(b.getAttribute(arg));
if (order == "asc") {
if (an > bn)
return 1;
if (an < bn)
return -1;
} else if (order == "desc") {
if (an < bn)
return 1;
if (an > bn)
return -1;
}
return 0;
});
$element.detach().appendTo($selector);
}
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Original Content
<table id="myTableOriginalContent">
<thead>
<tr><td></td></tr>
<tr>
<th><span>Name</span></th>
<th><span>Description</span></th>
</tr>
</thead>
</table>

Desired Result
<table id="myTable">
<thead>
<tr><td></td></tr>
<tr>
<th><span>Name</span></th>
<th><span>Description</span></th>
</tr>
</thead>
</table>

</body>
</html>

关于javascript - 如何在 html 表格的特定位置插入 <tr>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com