繁体   English   中英

如何在表中第 th 个元素的同一列中附加 td 元素?

[英]How to append td element in the same column of th element in a table?

我需要从 JSON 对象动态地将数据附加到表中。 添加标题作为 th 元素后,我发现很难在与相应的 th 元素相同的列中添加 tr 元素。 请帮我。

{
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
}

<table>
   <th>Category1</th>
   <th>Category2</th>
   <th>Category3</th>
</table>

现在,我需要在与它们对应的 th 元素相同的列中添加 td 标签中的项目。 喜欢:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM