从JavaScript中的表格单元格中获取价值...而不是jQuery

Gre*_*egH 41 html javascript

我无法相信这花了多长时间,但我似乎无法弄清楚如何在用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)

  • 实际上,上述解决方案并不完美。您不会在单元格中获得值,但也会获得整组格式化标签。 (3认同)
  • 完善!非常感谢.我在单元格中获得了文本框值,如下所示.var textboxVal = table.rows [r] .cells [c] .childNodes [0] .value; (2认同)

man*_*ear 6

我知道这就像多年以前的帖子,但由于没有选定的答案,我希望这个答案能给你带来你所期待的......

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)


Poi*_*nty 0

你有没有尝试过innerHTML

我倾向于使用getElementsByTagName()来查找<tr>元素,然后在每个元素上再次调用它来查找元素<td>。要获取内容,您可以使用innerHTML或适当的(特定于浏览器的)变体innerText