开发者问题收集

关于javascript:从javascript迭代渲染HTML以打印表格行不起作用,出现TypeError

2017-01-14
122

这里 学习。我正在尝试呈现此传感器数据的 HTML:

{
    "arduino": [{
        "location": "outdoor",
        "temperatureInC": "18.30",
        "temperatureInF": "64.94",
        "humidity": "61"
    }, {
        "location": "drawingRoom",
        "temperatureInC": "25.10",
        "temperatureInF": "77.18",
        "humidity": "40.80"
    }]
}

并使用此函数打印 HTML:

function renderHTML(data)
{
   var htmlString = "<table style='width:100%'><tr><th>Location</th><th>Temperature</th><th>Humidity</th></tr>";
   for (i = 0; i < data.length; i++){
      console.log(i);
      htmlString += "<tr><td>"+ data[i].location + "</td><td>" + data[i].temperatureInC + "&deg;C/ " + data[i].temperatureInF + "&deg;F </td> <td> " + data[i].humidity + "</td></tr>";
   htmlString += "</table>"
   console.log(htmlString);
   sensorDataContainer.insertAdjacentHTML('beforeend', htmlString);
   }
}

但发生了两个问题,

  1. 它只打印迭代的第一个项目,即室外
  2. 其次,它给出了以下错误:

TypeError: null is not an object (evaluating 'sensorDataContainer.insertAdjacentHTML')

我搞不懂这里发生了什么!我错过了什么?

2个回答

首先,您之所以看到第一行,只是因为您没有正确关闭 for 循环,请尝试以下方法:

function renderHTML(data)
{
   var htmlString = "<table style='width:100%'><tr><th>Location</th><th>Temperature</th><th>Humidity</th></tr>";
   for (i = 0; i < data.length; i++){
      console.log(i);
      htmlString += "<tr><td>"+ data[i].location + "</td><td>" + data[i].temperatureInC + "&deg;C/ " + data[i].temperatureInF + "&deg;F </td> <td> " + data[i].humidity + "</td></tr>";
   }
   htmlString += "</table>"
   console.log(htmlString);

   sensorDataContainer.insertAdjacentHTML('beforeend', htmlString); 
}

其次,您正在使用 sensorDataContainer 而没有对其进行初始化,因此您需要先对其进行初始化。

Tha'er AlAjlouni ثائر العجلوني
2017-01-14

您需要将最后三行移到 for 循环之外。

function renderHTML(data) {
    var htmlString = "<table style='width:100%'><tr><th>Location</th><th>Temperature</th><th>Humidity</th></tr>";
    for (i = 0; i < data.length; i++) {
        console.log(i);
        htmlString += "<tr><td>"+ data[i].location + "</td><td>" + data[i].temperatureInC + "&deg;C/ " + data[i].temperatureInF + "&deg;F </td> <td> " + data[i].humidity + "</td></tr>";
    }
    htmlString += "</table>";
    console.log(htmlString);
    sensorDataContainer.insertAdjacentHTML('beforeend', htmlString);
}
Nina Scholz
2017-01-14