【问题标题】:Grab table by ID and iterate over rows one at a time按 ID 抓取表并一次遍历一行
【发布时间】:2012-09-07 04:42:39
【问题描述】:

我想使用

var merch = document.getElementById('merch');

在我的网页上检索一个动态填充的表格。然后我想遍历表格,一次一行,抓住

<td> 

元素并将它们中的每一个作为字符串存储在数组中。每行都有自己的数组。

有人可以告诉我如何做到这一点吗?我确信有一个我在搜索中没有找到的简单方法。

提前感谢您的考虑。

【问题讨论】:

    标签: javascript dom dynamic iteration


    【解决方案1】:

    The working demo.

    var merch = document.getElementById('merch');
    
    // this will give you a HTMLCollection
    var rows = merch.rows;
    
    // this will change the HTMLCollection to an Array
    var rows = [].slice.call(merch.rows);   
    
    // if you want the elements in the array be string.
    // map the array, get the innerHTML propery.
    var rows = [].slice.call(merch.rows).map(function(el) {
        return el.innerHTML;
    });
    

    map

    【讨论】:

    • [].slice 是获取数组的切片方法,同Array.prototype.slice
    • 它是一个匿名函数,用作回调。
    • 检查这里,developer.mozilla.org/en-US/docs/DOM/table.rows 可以通过 google 轻松找到 :)
    • @RobG 我已经给出了map 的链接。在此代码中将主机对象视为本机对象是什么意思?欢迎举个例子,谢谢。
    • @nodirtyrockstar 如果你不使用 map,你可以使用普通的 for 循环,然后将元素推送到数组中。
    【解决方案2】:

    你会想要使用 jQuery 来做这件事,它会让事情变得更容易。然后你可以做这样的事情。

    HTML 表格

    <table id="iterateOverThisTable">
      <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
      </tr>
      <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
      </tr>
      <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
      </tr>
    </table>
    

    JS 文件(已包含 jQuery)

    $(function() {
      var rows = [];
    
      $("#tableToIterateOver tr").each(function() {
        var = cells = [];
    
        $(this).find('td').each(function() {
          cells.push($(this).text());
        });
    
        rows.push(cells);
      });
    })
    

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多