gpt4 book ai didi

javascript - 如何将 td 元素附加到表中 th 元素的同一列中?

转载 作者:行者123 更新时间:2023-11-28 07:29:16 26 4
gpt4 key购买 nike

我需要从 JSON 对象动态地将数据附加到表中。将标题添加为 th 元素后,我发现很难在与对应的 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 做到这一点? (我的问题比这个大。我把它简化了,这样就可以理解了。谢谢!)

最佳答案

开始吧,按运行代码片段并检查这是否适合您。

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>

关于javascript - 如何将 td 元素附加到表中 th 元素的同一列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com