这些示例之间有什么区别?为什么要使用一个示例而不是另一个示例来提高性能或浏览器兼容性?两者之间有不能做的事情吗?
txt="<address>"+
"<street>Roble Ave</street>"+
"<mtfcc>S1400</mtfcc>"+
"<streetNumber>649</streetNumber>"+
"<lat>37.45127</lat>"+
"<lng>-122.18032</lng>"+
"<distance>0.04</distance>"+
"<postalcode>94025</postalcode>"+
"<placename>Menlo Park</placename>"+
"<adminCode2>081</adminCode2>"+
"<adminName2>San Mateo</adminName2>"+
"<adminCode1>CA</adminCode1>"+
"<adminName1>California</adminName1>"+
"<countryCode>US</countryCode>"+
"</address>";
var d = document.createElement('div')
d.innerHTML = txt
console.log(d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(d.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
或
txt = "<address>" +
"<street>Roble Ave</street>" +
"<mtfcc>S1400</mtfcc>" +
"<streetNumber>649</streetNumber>" +
"<lat>37.45127</lat>" +
"<lng>-122.18032</lng>" +
"<distance>0.04</distance>" +
"<postalcode>94025</postalcode>" +
"<placename>Menlo Park</placename>" +
"<adminCode2>081</adminCode2>" +
"<adminName2>San Mateo</adminName2>" +
"<adminCode1>CA</adminCode1>" +
"<adminName1>California</adminName1>" +
"<countryCode>US</countryCode>" +
"</address>";
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
答案 0 :(得分:2)
一个潜在的问题是,分配给新创建元素的innerHTML
可以在txt
内部执行内联处理程序:
const txt = `
<address>
<street>Roble Ave</street>
...
</address>
<img src="nosrc" onerror="alert('evil');">
`;
const d = document.createElement('div')
d.innerHTML = txt
// navigate through d
如果txt
可以包含任意数据,则存在安全风险。 DOMParser
更安全,因为它没有此漏洞。
还请注意,您可以大大简化
d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue
到
d.querySelector('streetNumber').textContent
还请注意,jQuery不参与任何操作-这只是Javascript。