![](/img/trans.png)
[英]jQuery append new row to table - detecting existing rows but not adding new
[英]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.