我正在编写一个脚本,提示您输入低温和高温。单击添加温度时,它会显示今天的日期,低温和高温,以及低温和高温的平均值。每次输入这些临时值时,将显示最后一个日期之前的日期和那些临时值和平均值。当我尝试运行代码时,我得到了这个:TypeError: tempTable is null
。有什么建议吗?
(function() {
//Array to hold temp data
var temperatures = new Array();
// function which updates the array
function addTemp() {
var lowTemp = document.getElementById("lowTemp").value;
var highTemp = document.getElementById("highTemp").value;
if (lowTemp.length === 0 || highTemp.length === 0) {
alert("Valid low and high temperatures must be entered!");
} else {
document.getElementById("output").style.display = "block";
// Add new temperatures to the array
// Current date
var d = new Date();
if (temperatures.length == 0) {
// Current date if it is 1st temperature
temperatures.push(new Array(d.getMonth(), d.getDate(), d.getFullYear(), lowTemp, highTemp));
} else {
// 1 day before last date
newDate = temperatures[temperatures.length - 1][1] - 1;
temperatures.push(new Array(d.getMonth(), newDate, d.getFullYear(), lowTemp, highTemp));
}
// Create the output table
var tempTable = document.getElementById("tempTable");
tempTable.innerHTML = "<tr><th>Date</th><th>Low Temperatures</th><th>High Temperatures</th></tr>";
// Loop over the array and create the table
// Also calculate the averages
var avgLow = 0;
var avgHigh = 0;
temperatures.forEach(function(entry) {
var newRow = document.createElement('tr');
newRow.innerHTML = '<td>' + entry[0] + '/' + entry[1] + '/' + entry[2] + '</td><td align="right">' + entry[3] + '</td><td align="right">' + entry[4] + '</td>';
tempTable.appendChild(newRow);
avgLow += parseInt(entry[3]);
avgHigh += parseInt(entry[4]);
});
// Add the row for average
avgLow /= temperatures.length;
avgHigh /= temperatures.length;
avgLow = avgLow.toFixed(1)
avgHigh = avgHigh.toFixed(1)
var newRow = document.createElement('tr');
newRow.innerHTML = '<td>Averages</td><td align="right">' + avgLow + '</td><td align="right">' + avgHigh + '</td>';
tempTable.appendChild(newRow);
//Add row for lowest temp
var minTemp = Math.min.apply(lowTemp.value);
var key = lowTemp.indexOf(d);
var newRow = document.createElement('tr');
newRow.innerHTML = '<td colspan="3"> The lowest temp of' + minTemp + 'occured on' + key + '</td>';
tempTable.appendChild(newRow);
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addTemp;
} // End of init() function.
window.onload = init;
})();
&#13;
答案 0 :(得分:0)
错误意味着当你的代码执行时temptable
未设置,因为你的JS代码在加载DOM元素之前呈现。
var tempTable = document.getElementById("tempTable");
同时在init()
而不是DomContentLoaded
执行window.onload
。
document.addEventListener("DOMContentLoaded", function(event) {
init();
});