在Chrome上遇到Javascript getElementsByTagName问题

时间:2017-04-21 00:23:24

标签: javascript html xml google-chrome web

我遇到了在Chrome浏览器中获取xml标记名称长度的问题。当我尝试这个getElementsByTagName("auth:accountInfo")时,它在FF上工作正常,但不能处理chrome。如果我使用getElementsByTagName("accountInfo")它正在使用chrome但它不能用于FF。有人可以帮助我编写适用于两种浏览器的正确逻辑吗?以下是我的示例代码。

objXHR = XMLHttpRequest()
if(objXHR.status == 200)
        {
            var accountInfo = objXHR.responseXML.getElementsByTagName("auth:accountInfo");
            if (accountInfo.length > 0)
            {
                // do something
                }

1 个答案:

答案 0 :(得分:1)

使用getElementsByTagNameNS

getElementsByTagNameNS(authNS, 'accountInfo');

authNS,是您在XML文档中使用名称auth声明的namespaceURI。

请注意,您可以使用XPath查询//auth:accountInfo实现相同的功能,但是您需要传递namespaceResolver函数才能返回正确的nameSpaceURI。另请注意,此方法意味着更多代码,并且比其他DOM方法慢。

最后,您还可以使用querySelectorAll('*|accountInfo')实现此目的,但在这种情况下,所有带有tagName accountInfo的元素都将被选中,无论其名称空间如何。

let start = _ =>{
var doc = new DOMParser().parseFromString(sonnet, 'application/xml');
console.log('getElementsByTagNameNS');
console.log(doc.getElementsByTagNameNS("http://www.authors.com/", 'author')[0].outerHTML);

// Alternatively with XPath
function resolveNS(name) {
  if (name === 'auth') {
    return 'http://www.authors.com/'
  }
}
var query = doc.evaluate("//auth:author", doc, resolveNS, XPathResult.ANY_TYPE, null);
var elements = [];
var el;
while (el = query.iterateNext()) {
  elements.push(el);
}
console.log('XPATH');
console.log(elements[0].outerHTML)

// Or, with querySelectorAll
console.log('querySelectorAll');
console.log(doc.querySelectorAll('*|author')[0].outerHTML);
};

var sonnet = `<sonnet type='Shakespearean'>
  <auth:author xmlns:auth="http://www.authors.com/">
    <last-name>Shakespeare</last-name>
    <first-name>William</first-name>
    <nationality>British</nationality>
    <year-of-birth>1564</year-of-birth>
    <year-of-death>1616</year-of-death>
  </auth:author>
  <!-- Is there an official title for this sonnet? They're sometimes named after the first line. -->
  <title>Sonnet 130</title>
  <lines>
    <line>My mistress' eyes are nothing like the sun,</line>
    <line>Coral is far more red than her lips red.</line>
    <line>If snow be white, why then her breasts are dun,</line>
    <line>If hairs be wires, black wires grow on her head.</line>
    <line>I have seen roses damasked, red and white,</line>
    <line>But no such roses see I in her cheeks.</line>
    <line>And in some perfumes is there more delight</line>
    <line>Than in the breath that from my ...</line>
  </lines>
</sonnet>`;

start();

相关问题