簡體   English   中英

如何在jquery中的選定行的頂部追加新的表行

[英]How to append new table rows on top of selected row in jquery

我想在選定行的頂部附加表格行。 這是我嘗試過的

 function maintest() { let table; let row0; let row1; let cell0; let cell1; let input2; let button; table = $('<table>'); table.attr({ "id": "testTable" }); row0 = $('<tr>').attr({"id":"selectedRow"}); table.append(row0); cell0 = $('<td>'); row0.append(cell0); input2 = $("<input>").attr({"class":"input0"}); cell0.append(input2); cell1 = $('<td>'); row0.append(cell1); button = $("<button>").attr({"class":"btn"}).text("Button").click(function() { row1 = $('<tr>').insertBefore($("#selectedRow")); table.append(row1); let cell2 = $('<td>'); row1.append(cell2); let input3 = $("<input>").attr({"class":"input1"}); cell2.append(input3); }); cell1.append(button); $("#mainDiv").append(table); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <body onload="maintest()"> <div id="mainDiv"></div> </body>

我想在 selectedRow 之前插入該行,但它在該行之后添加了新行

注意:我正在使用 insertBefore 方法

問題是因為您調用了insertBefore() ,它完全按照您的要求工作,但隨后您立即調用append()將行移動到table的末尾。 要解決您的問題,只需刪除append()調用。

話雖如此,您應該注意,您可以通過鏈接方法調用並在可用的情況下使用appendTo()和內聯簽名來減少代碼的冗長。 嘗試這個:

 function maintest() { let $table = $('<table>').prop("id", "testTable"); let $row0 = $('<tr>').prop("id", "selectedRow").appendTo($table); let $cell0 = $('<td>').appendTo($row0); let $input2 = $("<input>").addClass("input0").appendTo($cell0); let $cell1 = $('<td>').appendTo($row0); let $button = $("<button>").addClass('btn').text("Button").click(function() { let $row1 = $('<tr>').insertBefore($("#selectedRow")); let $cell2 = $('<td>').appendTo($row1); let input3 = $("<input>").addClass("input1").appendTo($cell2); }).appendTo($cell1); $("#mainDiv").append($table); } maintest();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="mainDiv"></div>

請注意,這可以通過在 DOM 中創建虛擬內容並在必要時克隆它來進一步簡化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM