2010-03-22 42 views
2

所以我是XML DOM和JavaScript的初学者,但我遇到了一个问题。我正在使用该脚本在现有网站的表格中显示我的XML数据。问题出现在我的JavaScript代码中嵌套一个循环。JavaScript和XML Dom - 嵌套循环

这里是我的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> 

然后我用这个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("&nbsp;"); 
> 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> 

代码工作得很好,除了它只返回各自的第一个title元素作者。我有点理解它为什么这样做,但我不知道如何嵌套另一个循环,所以当脚本运行时,它显示作者的所有标题,而不仅仅是第一个。每当我尝试嵌套一个循环时,它就会破坏整个脚本。

+0

为什么使用document.write? – austincheney 2012-07-27 18:25:54

回答

1
getElementsByTagName("title")[0].childNodes[0].nodeValue 

这就是为什么。你只拿到第一个冠军。把另一个循环,将生成所有igetElementsByTagName("title")[i]

我的提示: 使用jquery并在3行中写你的代码没有这样的问题。

+0

谢谢Naugtur,我在jQuery方面经验不足,但是这很有帮助,我觉得这个问题很重要。我试图把这样的for循环: var y = x [i] .getElementsByTagName(“books”);对于(n = 0; n BSteck 2010-03-22 16:53:24