如何在tag?<table> </table>中显示数组值

时间:2012-08-29 13:11:51

标签: javascript html

我有这样的数组值。我想在HTML表格标签

中显示这些值
<script type="text/javascript">
var orderArray = [
    ["1","29-Aug-2012", "Product1", "client1"],
    ["2","29-Aug-2012", "Product2", "client2"],
    ["3","29-Aug-2012", "Product3", "client3"],
    ["4","29-Aug-2012", "Product4", "client4"],
    ["5","29-Aug-2012", "Product5", "client5"]
    ];

function display()
{
    for(i=0;i<ordertArray.length;i++)
    {
    //How to display values of array inside the div or table tag ???
    }
}

</script>


如何在div或table标签内显示数组的值???

4 个答案:

答案 0 :(得分:6)

orderArray项代表<tr>个元素,内部的每个项目代表<td>个元素。因此,您可以遍历orderArray创建<tr>,然后在每个循环中循环遍历其元素,创建<td> s:http://jsfiddle.net/h7F7e/

var table = document.getElementById("table");  // set this to your table

var tbody = document.createElement("tbody");
table.appendChild(tbody);
orderArray.forEach(function(items) {
  var row = document.createElement("tr");
  items.forEach(function(item) {
    var cell = document.createElement("td");
    cell.textContent = item;
    row.appendChild(cell);
  });
  tbody.appendChild(row);
});

答案 1 :(得分:2)

这样的事情会为你创建一个动态表:

// get handle on div
var container = document.getElementById('container');
// create table element
var table = document.createElement('table');
var tbody = document.createElement('tbody');
// loop array
for (i = 0; i < orderArray.length; i++) {
    // get inner array
    var vals = orderArray[i];
    // create tr element
    var row = document.createElement('tr');
    // loop inner array
    for (var b = 0; b < vals.length; b++) {
        // create td element
        var cell = document.createElement('td');
        // set text
        cell.textContent = vals[b];
        // append td to tr
        row.appendChild(cell);
    }
    //append tr to tbody
    tbody.appendChild(row);
}
// append tbody to table
table.appendChild(tbody);
// append table to container
container.appendChild(table);

使用document.createElement()element.appendChild()

Working example here

答案 2 :(得分:2)

使用table elements的DOM函数:

function display() {
    var table = document.createElement("table");
    for (var i=0; i<orderArray.length; i++) {
        var row = table.insertRow();
        for (var j=0; j<orderArray[i].length; j++) {
            var cell = row.insertCell();
            cell.appendChild(document.createTextNode(orderArray[i][j]));
        }
    }
    return table;
}

在DOM准备就绪时调用该函数,并将返回的表追加到某处。

答案 3 :(得分:1)

var table = "<table>"; // Open Table

for(i=0; i<orderArray.length; i++)
{
 table += "<tr>"; // Open Row

 for(i2=0; i2<orderArray[i].length; i2++) {
 {
  table += "<td>" + orderArray[i][i2] + "</td>"; // Each Column
 }

 table += "</tr>"; // Close Row
}

table += "</table>"; // Close Table