2013-03-25 25 views
0

我遇到問題使用簡單的'getElementsByClass'函數遍歷表單上的元素。我必須使用這個標題:Javascript getElementsByClass HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

我也必須使用IE8。

如果我刪除標題,該功能正常工作。我意識到錯誤的標籤不在正確的位置,但是如果我刪除它們,該功能也可以正常工作。還有更多的頁面,但這裏是一個精簡版:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 

<script type="text/javascript"> 
    function getElementsByClass(node,searchClass,tag) {  
     var classElements = new Array(); 
     var els = node.getElementsByTagName(tag); // use "*" for all elements 
     var elsLen = els.length; 
      alert("elsLen: " + elsLen);   
     var pattern = new RegExp("\\b"+searchClass+"\\b"); 
     for (i = 0, j = 0; i < elsLen; i++) {   
     if (pattern.test(els[i].className)) { 
    classElements[j] = els[i]; 
    j++; 
    } 
    } 
    alert("getElementsByClass: classElements.length: " + classElements.length); 
    return classElements; 
    } 
</script> 
</head> 
<body> 
<table> 
    <form name="formOne"> 
     <input type="button" value="click" onclick="getElementsByClass(document.formOne,'popupElement','*');" />   
     <input type="text" class="popupElement"> 
    </form>   

    <form name="formTwo"> 
     <table>     
     <input type="text" class="popupElement"> 
     <input type="text" class="popupElement"> 
     <input type="button" value="click2" onclick="getElementsByClass(document.formTwo,'popupElement','*');" /> 
    </form> 

上formOne火災正確的第一次調用getElementsByClass()並顯示警告框正確的價值觀。但在formTwo上的調用中,該函數在窗體上找不到任何元素。

我只是想弄清楚爲什麼發生這種情況,所以我可以開發一種解決方法。

+3

你可以使用已經存在的getElementsByClassName()方法嗎? – karaxuna 2013-03-25 20:04:52

+0

@karaxuna - 如果他想要支持IE8,則不需要,但可能應該在其他情況下使用它 – kevmc 2013-03-25 20:10:45

+1

[自己實現](http://stackoverflow.com/questions/7410949/javascript-document-getelementsbyclassname-compatibility-with-ie ) – James 2013-03-25 20:12:59

回答

0

首先,我無法在IE8上覆制它,它似乎是IE9的問題。

問題出在您提供的HTML上。由於某種原因,IE DOM解析器在結束標籤處出現混淆,因此正在創建一個空標籤(<>)。在你的情況下,表單最終成爲一個空標籤,從而產生以下輸出。

LOG: elsLen: 0 
LOG: getElementsByClass: classElements.length: 0 

試試看這個標記。

<html> 
<body> 
<table> 
<tbody> 
    <tr> 
     <td> 
      <form name="formOne"> 
       <input type="button" value="click" onclick="getElementsByClass(document.formOne,'popupElement','*');" />   
       <input type="text" class="popupElement" /> 
      </form> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <form name="formTwo"> 
       <table> 
        <tbody> 
         <tr> 
          <td> 
           <input type="text" class="popupElement"/> 
           <input type="text" class="popupElement"/> 
           <input type="button" value="click2" onclick="getElementsByClass(document.formTwo,'popupElement','*');" /> 
          </td> 
         </tr> 
        </tbody> 
       </table> 
      </form> 
     </td> 
    </tr> 
</tbody> 
</table> 
</body> 
</html> 

主要是我剛剛關閉所有的標籤,並遵循HTML 4.01 table schema