所以我是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(" ");
> 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元素作者。我有点理解它为什么这样做,但我不知道如何嵌套另一个循环,所以当脚本运行时,它显示作者的所有标题,而不仅仅是第一个。每当我尝试嵌套一个循环时,它就会破坏整个脚本。
为什么使用document.write? – austincheney 2012-07-27 18:25:54