使用javascript在html表的中间插入行

inserting row in the middle of a html table using javascript

本文关键字:中间 插入 javascript html 使用      更新时间:2023-09-26

我有一个包含两行的表。

<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>

我需要使用java脚本在第1行和第2行之间插入几行。我可以通过使用java脚本create元素来实现这一点。但是我希望使用字符串html内容添加新行。例如:

"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);

有这样的方法在中间添加行吗?

var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);

请在此处阅读:https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

使用jQuery。有一个函数insertAfter();

$("#row1").insertAfter("your html");

http://jquery.com/

var button = document.getElementById('insert');
var table = document.getElementById('table');
button.onclick = function() {
var position=Math.round(table.rows.length / 2);
var row = table.insertRow(position);
row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
} 
 **after that if u can use like that u can increment ur row id also:**

 var rowId = '#' + tableId + ' tr';
    var k = 0;
    $(rowId).each(function () {
        var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
        if (ObjInput != null) {
            for (var j = 0; j < ObjInput.length; j++) {
                var inputId = $(ObjInput[j]).attr('id');
                inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
                $(ObjInput[j]).attr('id', inputId);
                $(ObjInput[j]).attr('name', inputId);
            }
            k++;
        }
    });