SCRIPT5007 IE9 getElementsByTagName

时间:2011-07-11 11:14:44

标签: javascript internet-explorer-9

为什么这个简单的东西在IE 9中不起作用?它适用于FF和Chrome。

<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>joe@joe.com</email>
</BusinessCard>
</xml>

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

它失败了“xmldata.getElementsByTagName(”BusinessCard“)[0];”对于bizCard,结果为null。

2 个答案:

答案 0 :(得分:3)

我知道这有点晚了,但我遇到了类似的问题,您可能需要考虑将您的xml代码包装在div中,然后在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>joe@joe.com</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()协议

答案 1 :(得分:0)

我认为这是因为在IE中,具有非标准标签名称的元素不能包含其他元素。

尝试xmldata.canHaveChildren,它应该返回false