使用JavaScript数组生成html内容

时间:2019-03-22 09:58:13

标签: javascript html

var array = [
['name1', 'material1', 'number1', 'place1', 'country1'],
['name2', 'material2', 'number2', 'place2', 'country2']
];

这是js数组

<table>
    <tr>
        <th>Name</th>
        <th>Material</th>
        <th>Number</th>
        <th>Place</th>
        <th>Country</th>
    </tr>
</table>

这是我拥有的html表

现在我希望在我的数组中生成数组的值纯JS的表格。这怎么可能?

2 个答案:

答案 0 :(得分:0)

您可以循环到数组并使用<tr><td>创建HTML字符串,然后将它们应用于table元素的内部HTML:

var array = [
['name1', 'material1', 'number1', 'place1', 'country1'],
['name2', 'material2', 'number2', 'place2', 'country2']
];
var nHTML = document.querySelector('table').innerHTML;
array.forEach(function(arrItem){
  var td = '<tr>';
  arrItem.forEach(function(item){
    td += '<td>'+item+'</td>' ;
  });
  nHTML += td + '</tr>';
});
document.querySelector('table').innerHTML = nHTML;
<table border='1'>
    <tr>
        <th>Name</th>
        <th>Material</th>
        <th>Number</th>
        <th>Place</th>
        <th>Country</th>
    </tr>
</table>

答案 1 :(得分:0)

检查此提琴手:https://jsfiddle.net/a3r8ze0g/

您需要像这样遍历数组:

  

arr.forEach(function(elem){//其中arr是数组

var arr = [
['name1', 'material1', 'number1', 'place1', 'country1'],
['name2', 'material2', 'number2', 'place2', 'country2']
];

var tabla = document.getElementById('newTable');

arr.forEach(function(elem){

    var tr = tabla.insertRow();
  tr.innerHTML = '<td>'+elem[0]+'</td><td>'+elem[1]+'</td><td>'+elem[2]+'</td><td>'+elem[3]+'</td><td>'+elem[4]+'</td>';
})

var arr = [
['name1', 'material1', 'number1', 'place1', 'country1'],
['name2', 'material2', 'number2', 'place2', 'country2']
];

var tabla = document.getElementById('newTable');

arr.forEach(function(elem){
  
	var tr = tabla.insertRow();
  tr.innerHTML = '<td>'+elem[0]+'</td><td>'+elem[1]+'</td><td>'+elem[2]+'</td><td>'+elem[3]+'</td><td>'+elem[4]+'</td>';
})
<table id="newTable">
    <tr>
        <th>Name</th>
        <th>Material</th>
        <th>Number</th>
        <th>Place</th>
        <th>Country</th>
    </tr>
</table>