2011-07-11 74 views
0

爲什麼這個簡單的東西在IE 9中不起作用?它工作得很好,我FF和Chrome。SCRIPT5007 IE9 getElementsByTagName

<script language="javascript" type="text/javascript"> 
    function displayBusinessCardData() { 
     var xmldata = document.getElementById("xmldata1"); 
     var bizCard = xmldata.getElementsByTagName("BusinessCard")[0]; 

     var name = "Name: " + bizCard.getElementsByTagName("name")[0].firstChild.data; 
     var phone1 = "Phone: " + bizCard.getElementsByTagName("phone")[0].firstChild.data; 
     var phone2 = "Phone: " + bizCard.getElementsByTagName("phone")[1].firstChild.data; 
     var phone3 = "Phone: " + bizCard.getElementsByTagName("phone")[2].firstChild.data; 
     var email = "Email: " + bizCard.getElementsByTagName("email")[0].firstChild.data; 

     alert("BusinessCard Data: \n\n" + name + "\n" + phone1 + "\n" + phone2 + "\n" + phone3 + "\n" + email); 
    } 
</script> 

<xml id="xmldata1" style="display:none"> 
<BusinessCard> 
    <name>Joe Marini</Name> 
    <phone type="mobile">(415) 555-4567</phone> 
    <phone type="work">(800) 555-9876</phone> 
    <phone type="fax">(510) 555-1234</phone> 
    <email>[email protected]</email> 
</BusinessCard> 
</xml> 

<a href="javascript:displayBusinessCardData()">Show Business Card Data</a> 
</body> 

它失敗,並顯示「xmldata.getElementsByTagName(」BusinessCard「)[0];」結果bizCard爲空。

回答

0

我認爲這是因爲在IE中,具有非標準標籤名稱的元素不能包含其他元素。

嘗試一次xmldata.canHaveChildren,應該返回false

+0

Thx Luc。這簡直是​​愚蠢的MS。他們是那些引入XML數據島的人,現在他們不再支持它了。 – Irina

3

我知道這是有點晚了,但我遇到了類似的問題,你可能要考慮在一個div包裹你的XML代碼,再經過初始化它作爲一個XML文檔:

<div id="xmldata"> 
    <BusinessCard> 
     <name>Joe Marini</Name> 
     <phone type="mobile">(415) 555-4567</phone> 
     <phone type="work">(800) 555-9876</phone> 
     <phone type="fax">(510) 555-1234</phone> 
     <email>[email protected]</email> 
    </BusinessCard> 
</div> 

然後在你的函數使用的DOMParser對象來創建XML文檔:

function displayBusinessCardData() { 
    var xmlstring= document.getElementById("xmldata").innerHTML; 
    parser=new DOMParser(); 
    var bizCard = parser.parseFromString(xmlstring,"text/xml"); 

    var name = "Name: " + bizCard.getElementsByTagName("name")[0].firstChild.data; 
    var phone1 = "Phone: " + bizCard.getElementsByTagName("phone")[0].firstChild.data; 
    var phone2 = "Phone: " + bizCard.getElementsByTagName("phone")[1].firstChild.data; 
    var phone3 = "Phone: " + bizCard.getElementsByTagName("phone")[2].firstChild.data; 
    var email = "Email: " + bizCard.getElementsByTagName("email")[0].firstChild.data; 

    alert("BusinessCard Data: \n\n" + name + "\n" + phone1 + "\n" + phone2 + "\n" + phone3 + "\n" + email); 
} 

希望這有助於。我最主要的是,你可以從一個字符串中創建一個有效的xml對象。

最後一件事,它是不好的做法在你的A標籤中使用javascript:function()協議