javascript - 在jquery中添加到表行

标签 javascript jquery

我现在已多次阅读此主题:Add table row in jQuery ....并且仍然不明白为什么我无法附加到我刚刚创建的行:

var row = $('#sitesTable').append('<tr/>');
        row.append($('<td align="left"/>').text(k));
        row.append($('<td align="center"/>').text(v.length));

这只是创建一个空的 tr 标签而不附加到它:

<table class="sitesTable" id="sitesTable">
<tr></tr>
<th align="left">Site</th>
<th align="right">Total</th>
...

我感谢任何帮助,因为这开始让我发疯。

最佳答案

因为var row = $('#sitesTable').append('<tr/>');返回对表的引用,而不是新创建的行

你可以使用

var row = $('<tr/>').appendTo('#sitesTable');

var row = $('<tr/>').appendTo('#sitesTable');
$('<td align="left"/>').text('col-1').appendTo(row);
$('<td align="center"/>').text('col-2').appendTo(row);
// I prefer the above format for readability
//row.append($('<td align="left"/>').text('col-1'));
//row.append($('<td align="center"/>').text('col-2'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="sitesTable" id="sitesTable">
  <tr>
    <th align="left">Site</th>
    <th align="right">Total</th>
  </tr>
</table>

关于javascript - 在jquery中添加到表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48731107/

相关文章:

php - 需要在 php 中使用 jquery 获取选中的输入和复选框值

javascript - 如何在 Visual Studio 2013 中禁用 JavaScript 调试

javascript - 提取文章的主要内容(JavaScript)

javascript - 如何将 Vivus 监听器附加到 div 的滚动条上?

javascript - 使用 CasperJS 中的函数返回 iframe 内的链接

javascript - Jquery:在菜单悬停时更改不透明度

javascript - 当 <p> 标签中的文本发生变化时,如何检测或触发事件?

jQuery - 如何动态改变值?

jquery - 从 ajax json 填充数据表

javascript - 从回调函数内部访问 2D 数组 jquery 元素的索引