如何在表中元素的同一列中附加一个元素

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

本文关键字:元素 一列 一个      更新时间:2023-09-26

我需要从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>