如何在表中元素的同一列中附加一个元素
How to append td element in the same column of th element in a table?
我需要从JSON对象动态地向表追加数据。在添加标题作为元素之后,我发现很难在与对应的th元素相同的列中添加tr元素。请帮帮我。
{
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
}
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>
现在,我需要在列的td标记中添加与它们对应的th元素相同的项。如:
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
<tr>
<td>Item1</td>
</tr>
<tr>
<td>Item2</td>
</tr>
<tr>
<td>Item3</td>
</tr>
</table>
我如何使用jQuery做到这一点?我的问题比这更严重。我把它简化了以便能被理解。谢谢!)
给你,按下Run code snippet
,检查一下是否适合你。
var nodes = {
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
};
$(function(){
var th_elements = $('table').find('th'); // find <th> in HTML
th_elements.each(function(){ // Loop as much <th> found
var html = $.trim($(this).html()); // get HTML and compare with nodes key
$('table').append('<td>'+nodes[html]+'</td>'); // append data to table
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>
相关文章:
- 柱状图后面的一列
- 数据表通过分析一列的值对其进行排序
- Datatables-如何在未显示所有列的情况下禁用表中最后一列的排序
- 获取表中每行的一列的内容,然后循环访问每个内容
- 对象数组-与其他列数据相比,增加一列
- 在最初的查询/表格绘制中只提取谷歌电子表格的一列
- jQuery Datatables:单击一列时对另一列进行排序
- 我的砖石图像只显示在一列中
- 删除“;使用javascript从pentaho中的一列中选择“[”
- 使用 Javascript 在一列中更改属性内容
- jquery插件 - 已选择 - 多项选择不在一行中列出,而是列在一列中
- 单击包含按钮的最后一列时获取表的第一列值
- 排除行选择中的最后一列
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- 取消表中一列的onclick事件
- “搜索”文本仅考虑表格中的最后一列
- 如何将数组添加到对象中,但为每个数组元素过滤掉除一列之外的所有列
- 在jQuery中一次将元素从一列移动到另外两列
- 如何用Javascript为图表中的每一列添加更多的href元素
- 最后一列不总是显示在html表内bootstrap塌陷元素时,使用chrome浏览器