将数组中的元素添加到HTML表

时间:2016-08-25 21:25:52

标签: javascript html

我正在尝试使用数组中的值创建表。我能够获取数组中的值以显示在表中,但我不希望第一个数组中的值出现在表行中。

function generateTable() {
  //Build an array containing Customer records.
  var listOfActivities = [
    ["Checkbox", "Activity"],
    ["Alcatraz", "Golden Gate Bridge",
     "Golden Gate Park", "Fisherman's Wharf", "Lands End"]
  ];

  //Create a HTML Table element.
  var table = document.createElement("TABLE");
  table.border = "1";

  //Get the count of columns.
  for (var i = 0; i < listOfActivities.length; i++) {
    var columnCount = listOfActivities[0].length;
  }

  //Add the header row.
  var row = table.insertRow(-1);
  for (var i = 0; i < columnCount; i++) {
    var headerCell = document.createElement("TH");
    headerCell.innerHTML = listOfActivities[0][i];
    row.appendChild(headerCell);
  }

  //Add the data rows.
  for (var i = 0; i < listOfActivities[1].length; i++) {
    row = table.insertRow(-1);
    for (var j = 0; j < columnCount; j++) {
      var cell = row.insertCell(-1);
      cell.innerHTML = listOfActivities[j][i];
    }
  }

  var dvTable = document.getElementById("dvTable");
  dvTable.innerHTML = "";
  dvTable.appendChild(table);
}

generateTable();
<table id="dvTable"></table>

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

https://jsfiddle.net/d5coza47/

这就是我改变了

//Add the data rows.
for (var i = 0; i < listOfActivities[1].length; i++) {
    row = table.insertRow(-1);
    for (var j = 1; j < columnCount; j++) {
        var cell = row.insertCell(0);
        cell.innerHTML = listOfActivities[j][i];
        cell = row.insertCell(0);
        cell.innerHTML = "<input type='checkbox'>"
    }
}