Dynamic & Complex rowspan in HTML table

后端 未结 1 1755
青春惊慌失措
青春惊慌失措 2020-12-29 14:16

Link to JSFiddle

Here is my JSON format

{
    \"result\": {
        \"buildname1\": [{
            \"table1\": [\"xxx\",\"yyy\"]
        }, {
                


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 15:03

    I honestly had never used rowspan before, but after reading this stack answer I understood it much better - I would highly recommend you do the same. After that, it was just a matter of figuring out the order of the elements from JSON into the DOM.

    Here is a WORKING DEMO:

    var data = '{"result":{"buildname1":[{"table1":["xxx","yyy", "zzz"]},{"table2":["xxx","yyy"]}],"buildname2":[{"table1":["xxx","yyy", "zzz"]},{"table2":["xxx","yyy"]},{"table3":["xxx","yyy"]}], "buildname3":[{"table1":[]},{"table2":["xxx","yyy"]},{"table3":[]}], "buildname4":[]},"Build sets":"yyy","destinationPath":"xxx","status":1}';
    
    function generateTable(data) { //data is the parsed JSON Object from an ajax request
      data = JSON.parse(data);
      $("#test-table tbody").empty(); //Empty the table first
      Object.entries(data.result).forEach(([key, elem]) => {
        var baseHtml = "";
        var childrenHtml = "";
        var maxRowSpan = 0;
        elem.forEach((inner_elem, index) => {
          var [innerElemKey, arr] = Object.entries(inner_elem)[0];
          var elemRowSpan = Math.max(arr.length, 1);
          maxRowSpan += elemRowSpan;
    
          if (index !== 0) {
            childrenHtml += "";
          } 
          childrenHtml += ('' + innerElemKey + '');
          
          arr.forEach((child, indx) => {
            if (indx !== 0) {
              childrenHtml += "";
            }
            childrenHtml += ('' + child + '' + '');
          });
        });
        baseHtml += ('' + key + '');
        $("#test-table").append(baseHtml + childrenHtml);
      });
    }
    
    $(function() {
      generateTable(data);
    });
    td {
      border: 1px solid black;
    }
    
    
    Build Name Base Table Query List

    #Static HTML

    Build NameBase TableQuery List

    #Generated HTML

    Build Name Base Table Query List
    buildname1 table1 xxx
    yyy
    zzz
    table2 xxx
    yyy
    buildname2 table1 xxx
    yyy
    zzz
    table2 xxx
    yyy
    table3 xxx
    yyy

    0 讨论(0)
提交回复
热议问题