下面是我编写的代码,用于执行以下操作
每个表格行包含一个“+”按钮
当点击按钮时,代码应该找到被点击行的行索引
那么新行应该添加到选中行的 (rowindex+1) 位置。即,就在单击的行下方。
但是现在出现的问题是
按钮内的onclick函数不起作用,如果我把它写在里面,它就会起作用
“cell3”中按钮的 onclick 不起作用
由于我是 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,这是不可能的。您需要找到按钮父行的 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>
关于javascript - 使用 rowIndex 在单击的行下方插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27540107/