我正在尝试获取<tr>
表格中某个元素的子项。我需要获取每个单独的<td>
单元格。出于基础设施的原因,我不能使用 jQuery,只能使用 JavaScript。我的 JavaScript 看起来像这样:
var feeTable = document.getElementById("feeTable");
function gatherRowData() {
console.log("gathering row data");
var rows = this.parentNode.children; //This is where it fails.
var state = rows[0].innerText;
var county = rows[1].innerText;
var city = rows[2].innerText;
console.log("state: " + state);
document.getElementById("state_code").value = state;
document.getElementById("county_name").value = county;
document.getElementById("city_name").value = city;
}
//Loop through Vehicle Fee Changes to find any empty cells in county, city, or start date.
for (var i = 0; row = feeTable.rows[i]; i++) {
var county = row.cells[1];
var city = row.cells[2];
var startDate = row.cells[6];
if (county.innerText == "") {
county.style.backgroundColor = "#FF0000";
showError(invalidCells);
}
if (city.innerText == "") {
city.style.backgroundColor = "#FF0000";
showError(invalidCells);
}
if (startDate.innerText == "") {
startDate.style.backgroundColor = "#FF0000";
showError(invalidCells);
}
if (document.addEventListener) {
row.cells[8].addEventListener("click", gatherRowData);
} else if (document.attachEvent) { //Support for IE
row.cells[8].attachEvent("onclick", gatherRowData);
}
}
onClick 侦听器工作得很好,但是当我尝试获取表格行的子项时,它给了我错误:Error message: Unable to get value of the property '0': object is null or undefined
它在所有其他浏览器中工作正常,并且 IE9 没有打开兼容模式(它需要在兼容模式下运行) . 我错过了什么可以让我获得tr
元素的孩子?