1

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]、私のテーブルの 2 行目に対応する です。
  • これらの 2 つの間には がありchildNodes[2].childNodes[1]、これは[object Text]です。予想通りnodeNameです#text。ただし、nodeValue空白です。そのノードに何が含まれているか、またはその値にアクセスする方法がわかりません。
4

1 に答える 1

3
  • まず、innerHTMLそのような使用は避けてください。必要に応じて、DOM 要素を複製できます。

  • 次に、テーブルに がありません。<tbody>つまり、ブラウザがテーブルを挿入するため、ネスト.childNodesが不正確になります。

  • 3 つ目は、予期しないテキスト ノードがあることです。ページ内のすべてがノードとして表されるため、空白の書式設定を表すノードを回避する必要があります。

  • 最後に、テーブル要素は独自のカスタム コレクションを持っているため、ナビゲートが非常に簡単です.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
    
于 2013-03-14T23:06:10.537 に答える