如何从javascript中的数据表中获取数据?

时间:2010-07-14 17:38:12

标签: javascript

我想从javascript中的表(“displayTable”)中的一个名为“Limit”的列中提取数据(字符串)。我怎么做?

var table = document.getElementById('displayTable');    
var rowCount = table.rows.length;    
for (var i = 1; i < rowCount - 1; i++) {    
     var row = table.rows[i]["Limit"].ToString();
     alert(row);
     ...
}

3 个答案:

答案 0 :(得分:32)

这就是我在javascript中读表的方法。基本上我钻进了行,然后我能够深入到每行的单个单元格中。 这应该给你一个想法

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

更新 - 测试脚本

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

答案 1 :(得分:3)

使用Json&amp; jQuery的。它比oldschool javascript更容易

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

答案 2 :(得分:0)

此代码data中的是表数据的二维数组

let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))