我无法相信这花了多长时间,但我似乎无法弄清楚如何在用JavaScript迭代表格时从HTML表中提取单元格值.我正在使用以下内容进行迭代:
var refTab=document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在alert()调用中显示正确的调用以显示HTML表格中每个单元格的内容?这应该在JS中...不能使用jQuery.
bre*_*dan 68
function GetCellValues() {
var table = document.getElementById('mytable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这就像多年以前的帖子,但由于没有选定的答案,我希望这个答案能给你带来你所期待的......
if(document.getElementsByTagName){
var table = document.getElementById('table className');
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
alert('col html>>'+col.innerHTML); //Will give you the html content of the td
alert('col>>'+col.innerText); //Will give you the td value
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你有没有尝试过innerHTML?
我倾向于使用getElementsByTagName()来查找<tr>元素,然后在每个元素上再次调用它来查找元素<td>。要获取内容,您可以使用innerHTML或适当的(特定于浏览器的)变体innerText。