简体   繁体   中英

Is it possible to iterate through each item in an array and output as HTML?

I have a for loop that pushes targeted properties into an array if they pass a certain condition. I would like to create a table that outputs each item into its own row. The tricky part for myself is understanding how this can be done dynamically. It's easy to hardcode each item from the array and insert it into a row. But can this be done automatically using pure JS?

script.js

var myArray = [];
for (var i = 0; i < ccirdata.length; i++) {
    if (ccirdata[i].catType === 'I') {      
        myArray.push(ccirdata[i].catNum); 
    }
};

In the same file,

I have the outline for my table where I'm trying to insert the iterations from 'myArray':

var header =
             "<thead>" +
             "<tr>" +
             "<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
             "<td class='key'>" + " My Table:</td>" +
             "</tr>" +
             "</thead>";

var rows =
           "<tr>" +
           "<td class='key'><strong>" + <INSERT HERE> + "</strong></td>" +
            "</tr>" 

return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";

How can I create a new row dynamically for each item in myArray?

Here's one approach:

// using the same header code you provided

var rows = "";
myArray.forEach(function(item, index) {
    rows += "<tr>";
    rows += "<td class='key'><strong>" + item + "</strong></td>";
    rows += "</tr>";
});
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";

You can loop through myArray to create each row and concatenate them into a larger string.

var rows = "";
for (var r = 0; r < myArray.length; r++) {
    var row = "<tr>" + "<td class='key'><strong>" + myArray[r] + "</strong></td></tr>";
    rows = rows.concat(row);
}

Instead of building a text string to later set as HTML, I would opt for using a cleaner approach with insertRow like this:

<table>
  <thead>
    <tr><td>A header</td></tr>
  </thead>
  <tbody>
  </tbody>
</table>
<script type="text/javascript">
  var values = ['foo', 'bar', 'baz']; // Values to insert in table

  // Get a reference to the <tbody> element
  var tbody = document.querySelector('tbody');

  for (var i = 0; i < values.length; i++) {
    // This appends a new row to the <tbody> and returns a reference
    // to that element
    var row = tbody.insertRow();

    // Similarly to append a cell to the row
    var cell = row.insertCell();

    // Create a text node for the textual content and append it
    // to the cell
    var text = document.createTextNode(values[i]);
    cell.appendChild(text);
  }
</script>

As demonstrated in this JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM