简体   繁体   English

如何在jquery中的选定行的顶部追加新的表行

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

I want to append table row on top of selected row.我想在选定行的顶部附加表格行。 Here is what I tried这是我尝试过的

 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>

I want to insert the row before selectedRow but it adds new after this row我想在 selectedRow 之前插入该行,但它在该行之后添加了新行

Note :I am using insertBefore method注意:我正在使用 insertBefore 方法

The problem is because you call insertBefore() , which works exactly as you require, but then you immediately call append() which moves the row to the end of the table .问题是因为您调用了insertBefore() ,它完全按照您的要求工作,但随后您立即调用append()将行移动到table的末尾。 To fix your problem simply remove the append() call.要解决您的问题,只需删除append()调用。

That being said, you should note that you can make your code much less verbose by chaining method calls and using appendTo() and inline signatures where available.话虽如此,您应该注意,您可以通过链接方法调用并在可用的情况下使用appendTo()和内联签名来减少代码的冗长。 Try this:尝试这个:

 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>

Note that this could be simplified further by creating the dummy content in the DOM and cloning it when necessary.请注意,这可以通过在 DOM 中创建虚拟内容并在必要时克隆它来进一步简化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM