我想在另一行下方添加一行,但它是在最后添加的。
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<table style="width: 200px" border="1">
<tr>
<th style="width: 100px">A</th>
<th style="width: 100px">B</th>
</tr>
<tr id="info">
<td>Data1</td>
<td>Data2</td>
</tr>
<tr>
<th colspan="2">C</th>
</tr>
</table>
<br />
<button type="button" onclick="AddRow()">Add Row</button>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function AddRow() {
$('#info').parent().append('<tr><td>Data3</td><td>Data4</td></tr>');
}
</script>
我希望將其添加如下。有沒有辦法做到這一點?

uj5u.com熱心網友回復:
的父級tr#info是table自身。因此,當您append()將 table內容放在最后時。
要執行您需要的操作,請選擇#info并使用after()在目標之后直接插入內容:
jQuery($ => {
$('.add-row').on('click', () => {
$('#info').after('<tr><td>Data3</td><td>Data4</td></tr>');
});
});
table { width: 200px; }
th { width: 100px; }
<table border="1">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr id="info">
<td>Data1</td>
<td>Data2</td>
</tr>
<tr>
<th colspan="2">C</th>
</tr>
</table><br />
<button type="button" class="add-row">Add Row</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
另請注意,在上面的示例中,我將行內 CSS 移至外部樣式表,并將行內 JS 事件處理程式移至通過 jQuery 附加的不顯眼的處理程式。理想情況下,您的 HTML 應該不包含 HTML 以外的任何代碼。
uj5u.com熱心網友回復:
您應該使用 jQuery after() 函式 - https://api.jquery.com/after/
例子:
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<table style="width: 200px" border="1">
<tr>
<th style="width: 100px">A</th>
<th style="width: 100px">B</th>
</tr>
<tr id="info">
<td>Data1</td>
<td>Data2</td>
</tr>
<tr>
<th colspan="2">C</th>
</tr>
</table>
<br />
<button type="button" onclick="AddRow()">Add Row</button>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function AddRow() {
$('#info').after('<tr><td>Data3</td><td>Data4</td></tr>');
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/434317.html
