如何从表中获取数据?

IT技术 javascript
2021-03-14 09:40:39

如何从 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个回答

这就是我在 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>
cell4.innerHTML = 限制;什么是极限?我认为,如果您为 cell4.innerHTML 分配一个变量,您将获得该单元格中的内容(假设您正确设置了所有内容并且有实际数据)。
2021-04-17 09:40:39
我在代码段上取得了进展。innerHTML 似乎是空的,这很奇怪,因为这是我在 javascript 代码中输入数据时添加数据的方式。var cell4 = row.insertCell(3); cell4.innerHTML = 限制;
2021-04-29 09:40:39
@ user54197:我原始代码段中 rowLength 上的 -2 是我之前使用过的代码的残余......我很高兴它对你有用!
2021-05-02 09:40:39
好的,我刚刚创建了一个测试页面并测试了脚本。我编辑了我的原始答案以提醒我们表格中的每个单元格。从这里我认为你应该能够得到你需要的东西。
2021-05-04 09:40:39
我明白我哪里出错了。for 循环不需要 rowLength - 2 ... 至少在我的情况下。我真的很感激这个
2021-05-11 09:40:39

在这段代码中data是表数据的二维数组

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

使用 Json 和 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();