首页 > 解决方案 > xml getElementsByTagName 返回 null

问题描述

我正在尝试创建网页的一部分,通过将评论存储在 xml 文件中,使用 javascript 提取数据并设置循环参数,然后设置 html 来显示它,从而循环浏览评论。我的代码是:

xml布局:

<reviewlist>
<review>
<author>Author Name Here</author>
<comment>Author Comment Here</comment>
</review> <!-- i have 4 reviews in total -->
</reviewlist>

javascript和html:

function reviews() {

    if (window.XMLHttpRequest) {                                  
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");       
    }
    xmlhttp.open("GET", "../xml/Reviews.xml");
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;

    x = xmlDoc.getElementsByTagName("reviewlist")[0];   //pull all 'review' elements into a string
    var tot = x.childNodes.length[0];                   //pull the number of 'review' elements as an Int. This shows the total number of reviews to cycle through
    var i = 0;                                          //a counter which will be used to identify which review number to display

    var content = "current review no." + i;
    var author = "total reviews: " + tot;
    document.getElementById('review').innerHTML = content;
    document.getElementById('reviewer').innerHTML = author;

    var id = setInterval(revolve, 10000); //each time the function repeats, check that the counter is a lower number than the total number of reviews. If true, show the current review no and how many reviews there are in total.
    function revolve() {
        if (i << tot) {
            content = "current review no. " + i;
            author = "total reviews: " + tot;
            i++;
        } else {                         //when the counter and the total reviews variables are equal, reset counter to 0 and loop through the reviews again
            content = "current review no. " + i;
            author = "total reviews: " + tot;
            i = 0;
        }
        document.getElementById('review').innerHTML = content;
        document.getElementById('reviewer').innerHTML = author;
    }
}
<blockquote class="review" id="review" style="top:0;"></blockquote>
<p class="reviewer" id="reviewer" style="bottom:0;right:0;"></p>

在我的网络开发人员中,我收到错误“TypeError:无法读取 null 的属性 'getElementsByTagName'”,但我看不出哪里出错了。我可以做些什么来解决这个错误并最终让 tot 变量返回 4(我的 XML 文件中的评论数)?

标签: javascripthtmlajaxxml

解决方案


推荐阅读