【发布时间】:2020-08-26 20:40:43
【问题描述】:
我正在学习 W3 XML DOM 教程。我不明白为什么迭代会在输出中产生 1、3、5、7。我了解其他所有内容(我想!)有人可以帮忙解释一下吗?谢谢。
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, y, i, xlen, xmlDoc, txt;
xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("book")[0];
xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i < xlen; i++) {
if (y.nodeType == 1) {
txt += i + " " + y.nodeName + "<br>";
}
y = y.nextSibling;
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
输出是:
1 title
3 author
5 year
7 price
你好 Andy,这是 xml DOM 文件,来自https://www.w3schools.com/xml/dom_nodes.asp
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
针对 Carlos22 的回答的其他 cmets。对不起,卡洛斯,我还是不明白。
(y.nodeType ==1) 将始终返回 true,因为第一次出现 <book> 的子元素都是 type element (nodeType = 1)
第一个循环i = 0 所以txt 的值应该是0 title
第二个循环i = 1 所以0 title 应该与1 author 连接所以字符串txt 的值现在是0 title 1 author
第三个循环i = 2 txt 包含字符串0 title 1 author 2 year 等等。
我有时会变得非常愚蠢,所以请原谅!
【问题讨论】:
-
你能在这个例子中包含你的 xml 吗?
-
你好安迪,这是 xml DOM:
标签: javascript xml dom