javascript - 使用 DOM 探索表格

标签 javascript dom

我正在构建一个我想使用 DOM 探索的动态 html 表格。这是表格的代码:

<table id='nameTable'>
  <col width='5%'/>
  <col width='40%'/>
  <col width='40%'/>
  <col width='5%'/>
  <tr>
    <th rowspan='1' colspan='1'>Modify:</th>
    <th colspan='2'>Name Set Title: <span id="setTitle"><?php echo $setTitle ?></span></th>
    <th rowspan='1' colspan='1'>Remove:</th>
  </tr>
  <tr>
    <th rowspan='1' colspan='1'><input type='checkbox' name='' value='' /> All</th>
    <th colspan='2'>Tags: <span id="tags"><?php
      foreach ($tagArray as $tag){
        echo $tag." ";
      }?></span>
    </th>
    <th rowspan='1' colspan='1'><input type='checkbox' name='' value='' /> All</th>
  </tr>
    <?php 
      foreach ($nameArray as $pair){
        echo
        "<tr>
          <td><input type='checkbox' name='' value=''/></td>
          <td>".$pair[0]."</td>
          <td>".$pair[1]."</td>
          <td><input type='checkbox' name='' value=''/></td>
        </tr>";
      }
    ?>
</table>

在上面,$nameArray是一个数组数组,每个子数组包括名字和姓氏。

我正在尝试使用 DOM 访问 HTML 表格的各种元素。我在我的页面中内置了一个 <p id='test'></p>测试区,我可以在其中查看各种 DOM 语句的含义,例如通过执行 document.getElementById('test').innerHTML=document.getElementById('nameTable').childNodes[2].childNodes[1].innerHTML;

我无法想象 childNodes .更具体地说:

  • getElementById('nameTable').childNodes[2].childNodes[0][object HTMLTableRowElement] ,我可以用 innerHTML 得到值.其中包含表格的标题等。
  • childNodes[2].childNodes[2]也是一个[object HTMLTableRowElement]对应于我表格​​的第二行。
  • 这两者之间是 childNodes[2].childNodes[1] ,这是一个 [object Text] .它的nodeName#text , 正如预期的那样。然而,它的 nodeValue是空白的。我不明白该节点包含什么或如何访问它的值。

最佳答案

  • 首先,避免使用 innerHTML像那样。如果需要,您可以克隆 DOM 元素。

  • 其次,您的表缺少 <tbody> ,这意味着浏览器将为您插入它,使您的嵌套 .childNodes不准确。

  • 第三,是的,在您可能意想不到的地方会有文本节点。页面中的所有内容都表示为一个节点,因此您需要处理表示空白格式的节点。

  • 最后,表格元素非常容易导航,因为它们有自己的自定义集合,所以使用这些元素而不是 .childNodes .这样也解决了文本节点的情况。

    table.rows[]        // collection of rows in the table
    
    table.tBodies[]     // collection of tbody elements in the table
    
    table.tBodies[0].rows[]           // collection of rows in the first tbody
    
    table.tBodies[0].rows[0].cells[]  // collection of cells in the first row
                                      //                     in the first tbody
    
    table.tHead         // thead element
    table.tHead.rows... // as above
    
    table.tFoot         // tfoot element
    table.tFoot.rows... // as above
    

关于javascript - 使用 DOM 探索表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15421822/

相关文章:

javascript - 将鼠标悬停在具有 id 的 <img> 上时如何按 id 显示 <p>

javascript - 根据 Firebase 数据创建列表

javascript - 有没有办法使用 JavaScript 引入 Internet Explorer 条件注释?

jquery - jQuery : text() and html() ? 有什么区别

javascript - 为每个列表元素生成不同的、随机颜色的 DIV

javascript - 多字段计算

javascript - Socket.io双室

javascript - 如何暂停 Spinkit 动画?

javascript - Webpack:构建需要很长时间

javascript - 如何将 &lt;script&gt; 附加到 HTML DOM 中的当前位置