html - 带有 HTML 表格标记的 Jquery HTML 或 AFTER 或 APPEND
问题描述
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
标签。
我tr
用id=tblGrid定义了你的标签作为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>
推荐阅读
- replace - Microsoft Word:使用通配符查找和替换
- python - 强制 CNN 过滤器查看非相邻数据组合
- linux - postgres + 如何删除配置单元元存储的密码并设置新密码
- javascript - 为什么一个类在另一个类构造函数中被错误地提升
- amazon-web-services - aws-cdk LambdaRestApi:最终策略大小大于限制
- javascript - 如何正确地将纯 JS 文件导出和导入到另一个 JS 文件中?
- python - 从 OpenCV 触发的本地计算机上的“找不到相机”
- android - Android:用于仪器测试的不同 applicationId
- sql-server - 为什么我的代码不采用“-”而是采用“+”
- c# - .Net Core 3.1.5 无法连接到 API