动态附加多个TR

时间:2017-02-09 10:21:55

标签: javascript jquery arrays json html-table

我有以下数组:

arr = [{
  "ID": 1,
  "animals": {
    "dog": {
      "color": "brown",
      "age": 5
    },
    "cat": {
      "color": "white",
      "age": 3
    }
  }
}, {
  "ID": 2,
  "animals": {
    "cat": {
      "color": "black",
      "age": 7
    }
  }
}, {
  "ID": 3,
  "animals": {
    "mouse": {
      "color": "white",
      "age": 1
    },
    "dog": {
      "color": "black",
      "age": 9
    },
    "cat": {
      "color": "grey",
      "age": 4
    }
  }
}]

我需要制作这张表:

desired table

或代码:

<table border="1" id="myTab">
  <tr>
    <td>ID</td>
    <td>Animal</td>
    <td>Color</td>
    <td>Age</td>
  </tr>
  <tr>
    <td rowspan="2">1</td>
    <td>cat</td>
    <td>3</td>
    <td>white</td>
  </tr>
  <tr>
    <td>dog</td>
    <td>5</td>
    <td>brown</td>
  </tr>
  <tr>
    <td rowspan="1">2</td>
    <td>cat</td>
    <td>7</td>
    <td>black</td>
  </tr>
  <tr>
    <td rowspan="3">3</td>
    <td>mouse</td>
    <td>1</td>
    <td>white</td>
  </tr>
  <tr>
    <td>dog</td>
    <td>9</td>
    <td>black</td>
  </tr>
  <tr>
    <td>cat</td>
    <td>4</td>
    <td>grey</td>
  </tr>
</table>

Here我学会了如何合并多个tr的正确方法。

但是,它仍然不适用于我的例子:

$.each(arr, function(key, value) {
  var rowspan = Object.keys(arr[key].animals).length;

  var tr = "";
  c = 0;
  $.each(value, function(key2, value2) {
    if (key2 != "animals") {
      if (rowspan < 1) {
        rowspan = 1;
      }
      tr += '<td rowspan=' + rowspan + '>' + value2 + '</td>';
    } else {
      $.each(value2, function(key3, value3) {
        var tr2_temp = "";

        tr2_temp += "<td>" + key3 + "</td>";
        $.each(value3, function(key4, value4) {
          tr2_temp += "<td>" + value4 + "</td>";
        });

        if (c == 0) {
          $('#myTab tr:eq(' + parseInt(key + 1) + ')').append(tr2_temp)
          c++;
        } else {
          $('#myTab tr:eq(' + parseInt(key + 1) + ')').after(tr2_temp)
          c = 0;
        }
      });
    }
  });
  $('#myTab > tbody:last-child').append('<tr>' + tr + '</tr>');
});

Here is a fiddle

2 个答案:

答案 0 :(得分:1)

虽然我建议您不要将动物类型用作属性名称,因为如果您有多个相同类型的动物但是使用可能名为type的属性,则会导致问题。值dog, cat, etc..,使用您现有的条件,您可以执行以下操作。

另外,我建议你首先写入内存中的变量,然后单独附加到DOM。

arr = [{
    "ID": 1,
    "animals": {
        "dog": {
            "color": "brown",
            "age": 5
        },
        "cat": {
            "color": "white",
            "age": 3
        }
    }
}, {
    "ID": 2,
    "animals": {
        "cat": {
            "color": "black",
            "age": 7
        }
    }
}, {
    "ID": 3,
    "animals": {
        "mouse": {
            "color": "white",
            "age": 1
        },
        "dog": {
            "color": "black",
            "age": 9
        },
        "cat": {
            "color": "grey",
            "age": 4
        }
    }
}]

var rowspanTemplate = '<tr><td rowspan="{0}">{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>'
var simpleTemplate = '<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>'
var $newRows = $('<div></div>');

$.each(arr, function(key, value) {
    var newRow;
    var animalTypes = Object.keys(value.animals);
    var i;
    var animalType;

    for (i = 0; i < animalTypes.length; i++) {
        animalType = animalTypes[i];

        if (i === 0) {
            newRow = rowspanTemplate
                .replace('{0}', animalTypes.length)
                .replace('{1}', value.ID)
                .replace('{2}', animalType)
                .replace('{3}', value.animals[animalType].color)
                .replace('{4}', value.animals[animalType].age)
        } else {
            newRow = simpleTemplate
                .replace('{0}', animalTypes[i])
                .replace('{1}', value.animals[animalType].color)
                .replace('{2}', value.animals[animalType].age)
        }

        $newRows.append($(newRow));
    }
})

$('#myTab').append($newRows.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="myTab">
  <tr>
    <td>ID</td>
    <td>Animal</td>
    <td>Color</td>
    <td>Age</td>
  </tr>
</table>

答案 1 :(得分:0)

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
arr = [{
  "ID": 1,
  "animals": {
    "dog": {
      "color": "brown",
      "age": 5
    },
    "cat": {
      "color": "white",
      "age": 3
    }
  }
}, {
  "ID": 2,
  "animals": {
    "cat": {
      "color": "black",
      "age": 7
    }
  }
}, {
  "ID": 3,
  "animals": {
    "mouse": {
      "color": "white",
      "age": 1
    },
    "dog": {
      "color": "black",
      "age": 9
    },
    "cat": {
      "color": "grey",
      "age": 4
    }
  }
}]

function getAttr(obj) {
 var props;
 for (var prop in obj) {
    props += '<td>'+obj[prop]+'</td>';
  }
  return props;
}

function extractChildren(animal,obj) {
    return '<td>'+animal+'</td>' + getAttr(obj) + '';
}
function addRows() {
  for(var i=0; i<arr.length; i++) {
    var children = [];
    var rows = 0;

    for (var prop in arr[i].animals) {
      rows++;
      children.push(extractChildren(prop,arr[i].animals[prop]));
    }
    $('#tbl tbody').append(
    `<tr>
        <td rowspan="`+rows+`">`+ arr[i].ID+ `</td>`+children[0]+`
    </tr>`
    );
    children.shift();
    for(var j=0; j<children.length; j++) {
        $('#tbl tbody').append(`<tr>`+children[j]+`</tr>`);
    }
    }
}
$( document ).ready(function() {
    addRows();
});
</script>
<table id="tbl" border="1">
  <thead>
    <th>ID</th>
    <th>Animal</th>
    <th>Colour</th>
    <th>Age</th>
  </thead>
  <tbody>
  </tbody>