如何解决Jquery HTML 或 AFTER 或 APPEND with HTML table 标签
https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_after2
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function afterText() {
$("#tblGrid").html("<td>NameName2</td><td>Budget Value 2</td></tr><tr><td>NameName3</td><td>Budget Value 3</td>");
}
</script>
</head>
<body>
<table>
<tbody>
<th><h4>Name Heading</h4></th>
<th>
<table>
<thead>
<tr>
<th>Budget Heading</th>
</tr>
</thead>
</table>
</th>
<tr id="tblGrid"></tr>
<tr><td>NameName1</td><td>Budget Value 1</td></tr>
</tbody>
</table>
<button onclick="afterText()">Button</button>
</body>
</html>
点击按钮后输出是这样的:
名称标题预算标题
NameName3 预算值 3
NameName1 预算值 1
按钮
您能否帮助理解数字为“2”的值的去向?
预期输出:
名称标题预算标题
NameName2 预算值 2
NameName3 预算值 3
NameName1 预算值 1
按钮
此外,每次我们点击按钮时,不应该追加 2 和 3,而是清除旧的迭代值。请提出建议!
解决方法
您的 html 表格结构有点不正确。我更改了 thead
标签的结构。并且您不需要为此使用 h4
标记。
我使用 id=tblGrid 将您的 tr
标签定义为 tbody
标签。
此外,您正在使用 html()
方法。但是这种方法覆盖内容。最好使用 append()
方法。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function afterText() {
$("#tblGrid").append("<tr><td>NameName2</td><td>Budget Value 2</td></tr><tr><td>NameName3</td><td>Budget Value 3</td></tr>");
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name Heading</th>
<th>Budget Heading</th>
</tr>
</thead>
<tbody id="tblGrid">
<tr>
<td>NameName1</td>
<td>Budget Value 1</td>
</tr>
</tbody>
</table>
<button onclick="afterText()">Button</button>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。