【问题标题】:Having an issue with Javascript getElementsByTagName on chrome在 chrome 上遇到 Javascript getElementsByTagName 问题
【发布时间】:2017-09-17 19:43:44
【问题描述】:
我在 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
}
【问题讨论】:
-
这个好像和namespace组件有关,你有没有考虑改用XPath?
-
标签:
javascript
html
xml
google-chrome
web
【解决方案1】:
使用getElementsByTagNameNS。
getElementsByTagNameNS(authNS, 'accountInfo');
authNS,是您在 XML 文档中使用名称 auth 声明的命名空间URI。
请注意,您可以使用XPath 查询//auth:accountInfo 实现相同的目的,但是您需要传递一个namespaceResolver 函数来返回正确的nameSpaceURI。另请注意,此方法意味着更多代码,并且比其他 DOM 方法慢。
最后,您也可以使用querySelectorAll('*|accountInfo') 实现此目的,但在这种情况下,将选择所有带有标签名称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();