使用 rowIndex 在单击的行下方插入新行


Insert new row just below the clicked row with the use of rowIndex

下面是我写的代码,用于执行以下操作

  • 每个表格行都包含一个"+"按钮

  • 单击
  • 按钮时,代码应找到单击的行的行索引

  • 然后,应将新行添加到 (rowindex+1( 的位置。 即,就在单击的行下方。

但现在出现的问题是

  • 按钮内的onclick功能不起作用,如果我把它写在里面那么它将起作用

  • 单击"单元格3"中的按钮不起作用

由于我是 php 的初学者,也是 javascript 的初学者,任何人都可以帮我详细解释一下吗?

<script>
function myFunction(x) {
var table = document.getElementById("myTable");
var rowno=x.rowIndex;
alert(rowno);
var row = table.insertRow(rowno+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = '<input type="text"s name="txt1">';
cell2.innerHTML = '<input type="text" name="txt2">';
cell3.innerHTML = '<input type="button" name="btn" value="+" onclick="myFunction(this)">';
}
</script>
<table id="myTable" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
<td><button onclick="myFunction(this)">+</button></td>
 </tr>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
<td><button onclick="myFunction(this)">+</button></td>
</tr>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
<td><button onclick="myFunction(this)">+</button></td>
</tr>
</table>

您正在将按钮传递给函数并尝试查找其 rowIndex,这是不可能的。您需要找到按钮父行的行索引。我已经修改了javascript代码来选择它。这应该有效。

<script type="text/javascript">
    function myFunction(x) {
        var table = document.getElementById("myTable");
        var rowno = x.parentNode.parentNode.rowIndex; //this selects the button's parent row        
        alert(rowno);
        var row = table.insertRow(rowno + 1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        cell1.innerHTML = '<input type="text"s name="txt1">';
        cell2.innerHTML = '<input type="text" name="txt2">';
        cell3.innerHTML = '<input type="button" name="btn" value="+" onclick="myFunction(this)">';
    }
</script>