首页 > 解决方案 > 带有 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,而是清除旧的迭代值。请提出建议!

标签: htmljqueryhtml-tablejquery-selectors

解决方案


您的 html 表结构略有不正确。我改变了thead标签的结构。你不需要为此使用h4标签。

trid=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>


推荐阅读