动态生成的行未添加到 table html

Dynamiclly generated rows not added to table html

我想知道为什么如果我使用 Jquery 添加一个新行到 table ,如果我检查页面的源代码,新添加的行不会添加到 table . 我想要一种将新行添加到 table 的方法。 这是 jquery 代码:

$("#button").click(function(){
            $("table >tbody").append($('<tr>')).append($('<td>')).append("new row");
        });

和table:

<table>
    <tbody>
    </tbody>
</table>

使用这个:

<table id="yourtableid"><tbody></tbody><table>

$("#button").click(function(){
   $("#yourtableid tbody").append($('<tr>')).append($('<td>')).text("new row");
});

TEST HERE

我建议:

$("#button").click(function() {
  // create a <tr> element:
  $('<tr>', {
    // set its html:
    'html' : '<td>New row</td>'
  // append the <tr> to the <tbody>:
  }).appendTo('table > tbody');
});

$("#button").click(function() {
  $('<tr>', {
    'html' : '<td>New row</td>'
  }).appendTo('table > tbody');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">button</button>
<table>
  <tbody>
  </tbody>
</table>

原因是你原来的代码:

$("#button").click(function() {
  $("table > tbody").append($('<tr>')).append($('<td>')).append("new row");
});

不起作用是因为 append() returns 新内容被附加到的元素(在本例中是 <tbody>,所以所有元素和 textContent 都是附加到该元素(创建无效 HTML)。

$("#button").click(function() {
  $("table > tbody").append($('<tr>')).append($('<td>')).append("new row");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">button</button>
<table>
  <tbody>
  </tbody>
</table>

参考文献: