[英]JavaScript and XML Dom - Nested Loop
So I'm a beginner in XML DOM and JavaScript but I've run into an issue. 所以我是XML DOM和JavaScript的初学者,但是遇到了一个问题。 I'm using the script to display my XML data in a table on an existing site.
我正在使用脚本将XML数据显示在现有站点上的表中。 The problem comes in nesting a loop in my JavaScript code.
问题出在我的JavaScript代码中嵌套了一个循环。
Here is my XML: 这是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<book_list>
<author>
<first_name>Mary</first_name>
<last_name>Abbott Hess</last_name>
<books>
<title>The Healthy Gourmet Cookbook</title>
</books>
</author>
<author>
<first_name>Beverly</first_name>
<last_name>Bare Bueher</last_name>
<books>
<title>Cary Grant: A Bio-Bibliography</title>
<title>Japanese Films</title>
</books>
</author>
<author>
<first_name>James P.</first_name>
<last_name>Bateman</last_name>
<books>
<title>Illinois Land Use Law</title>
</books>
</author>
</book_list>
I then use this JavaScript code to read and display the data: 然后,我使用以下JavaScript代码来读取和显示数据:
> <script type="text/javascript"> if
> (window.XMLHttpRequest) {
> xhttp=new XMLHttpRequest(); } else
> // Internet Explorer 5/6 {
> xhttp=new
> ActiveXObject("Microsoft.XMLHTTP");
> } xhttp.open("GET","books.xml",false);
> xhttp.send("");
> xmlDoc=xhttp.responseXML;
>
> document.write("<table>"); var
> x=xmlDoc.getElementsByTagName("author");
> for (i=0;i<x.length;i++) {
> document.write("<tr><td>");
> document.write(x[i].getElementsByTagName("first_name")[0].childNodes[0].nodeValue);
> document.write(" ");
> document.write(x[i].getElementsByTagName("last_name")[0].childNodes[0].nodeValue);
> document.write("</td><td>");
> document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
> document.write("</td></tr>"); }
> document.write("</table>"); </script>
The code works well except it only returns the first title element of each author. 该代码运行良好,只返回每个作者的第一个title元素。 I somewhat understand why it's doing that, but I don't know how to nest another loop so when the script runs it displays all the titles for an author, not just the first.
我有点理解为什么这样做,但是我不知道如何嵌套另一个循环,因此当脚本运行时,它将显示作者的所有标题,而不仅仅是第一个。 Whenever I try to nest a loop it breaks the entire script.
每当我尝试嵌套循环时,它都会破坏整个脚本。
getElementsByTagName("title")[0].childNodes[0].nodeValue
that's why. 这就是为什么。 You take the first title only.
您只能获得第一个标题。 Put another loop that will generate all
i
for getElementsByTagName("title")[i]
放置另一个将为
getElementsByTagName("title")[i]
生成所有i
循环
My tip: use jquery and write Your code in 3 lines without problems like that. 我的提示:使用jquery并分三行编写您的代码,而不会出现类似问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.