項目中用javascript操作DOM遇到的問題

調用項目中已有的js,將表格的的樣式設置成間隔行顯示不同的顏色。

如下圖:

 

代碼如下:

 

<body class="shadow_bg02" οnlοad="initialize(document.getElementById('list_table'));">
<div class="DIVoverflow">
 <table id="list_table" border="0" cellpadding="0" cellspacing="1" width="100%" style="font-size:12px;background: #CCCCCC;">
  <!-- 如果從歷史記錄列表進入的話,則有返回按鈕;如果是從審批歷史查詢界面進入的話則沒有返回按鈕 -->
  <c:if test="${empty goBackBtn}">
   <tr bgcolor="#FFFFFF"><td colspan="6" align ="right"><input type="button" value="返回" class="button_back" οnclick="goback()"/> </td></tr>
  </c:if>
  
  <tr bgcolor="#FFFFFF">
   <td nowrap colspan="1"> <strong>名稱:</strong></td><td colspan="5">${freeEval.creater_org}</td>
  </tr>
  <tr bgcolor="#FFFFFF">
   <td nowrap> <strong>AAA:</strong></td>
   <td colspan="5"> ${freeEval.managerOrganization }</td>
  </tr>
  <tr bgcolor="#FFFFFF">
   <td nowrap > <strong>BB:</strong></td>
   <td colspan="5"> ${freeEval.corpname }</td>
  </tr>
  <tr bgcolor="#FFFFFF">
   <td nowrap> <strong>CC:</strong></td>
   <td colspan="5"> ${freeEval.accountType }</td>
  </tr>
 </table>
 </form>
</div>
</body>


initialize方法如下:

function initialize(tableElement) {
 if(tableElement){
     for(var i = 1; i<tableElement.childNodes[0].childNodes.length; i++){
      if (i%2 == 0) {
       tableElement.childNodes[0].childNodes[i].bgColor = "#f7f7f7";
      } else {
       tableElement.childNodes[0].childNodes[i].bgColor = "#ffffff";
      }
     }
 }
}


 

沒有得到想要出現的結果。

最後經檢驗alert(tableElement.childNodes[0].nodeType);發現彈出nodeType爲8,通過查找文檔知道Node是註釋類型。

所以原因是:多了一行註釋引起的結果。把<!-- 如果從歷史記錄列表進入的話,則有返回按鈕;如果是從審批歷史查詢界面進入的話則沒有返回按鈕 -->去掉就成功了。

同時,tableElement.childNodes[0]代表的是table下面第一個tbody。

2012-05-28 增加備註:tableElement.childNodes[0]代表的是table下面的第一個節點,也就是說如果表格設置了<thead><tbody><tfoot>的話,則就是<thead><tbody><tfoot>三個中最前面的那個。如果表格沒有設置<thead><tbody><tfoot>的話,則默認的把表格的內容放入<tbody>中,也就是tableElement.childNodes[0]代表table下面第一個tbody。

中設置的

記錄下,希望以後不犯錯了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章