ina*_*naz -1 html javascript jquery dom
我有一个有行的表.在此表中,某些行的跨度为"add"类.当我点击"添加"时,我想动态创建一个新行.代码可以工作,但是当一个新行生成它时,它会在我的表的末尾.如何更改我的代码以仅在单击的行下添加新行,而不是在表的末尾?
这是我的代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table id="prices-table" border="1">
<tr>
<td>1</td>
<td>Title<span class="add"><font color="red">add+</font></span></td>
<td>price</td>
</tr>
<tr>
<td>1</td>
<td>Title </td>
<td>price</td>
</tr>
</table>
<script>
$(document).ready(function () {
$(".add").click(function () {
$(this).closest('#prices-table')
.append('<tr><td>newrow</td><td>newrow</td><td>newrow</td></tr>');
});
})
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以使用closest到tr,然后只需更换append用after.
$(".add").click(function() {
$(this).closest('tr').after('<tr><td>newrow</td><td>newrow</td><td>newrow</td></tr>');
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="prices-table" border="1">
<tr>
<td>1</td>
<td>Title<span class="add"><font color="red">add+</font></span></td>
<td>price</td>
</tr>
<tr>
<td>1</td>
<td>Title</td>
<td>price</td>
</tr>
</table>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
549 次 |
| 最近记录: |