简体   繁体   中英

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

Note :I am using insertBefore method

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 . To fix your problem simply remove the append() call.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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