javascript - 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 文件中的评论数)?
解决方案
推荐阅读
- numpy - 从 2d numpy 数组的每一行中删除指定的列索引
- javascript - 访问与数组中的项同名的对象——Javascript
- git - 在不导航到存储库目录的情况下执行 git pull
- angular - 在 Angular 6 及以上版本中使用 webpack 好还是由 ng-build prod 处理?
- javascript - 如何导入自定义 Js 文件的所有方法
- python - 如何有效地访问熊猫中满足条件的第一次和最后一次出现索引
- forms - 控制器操作 - 重定向到另一个模板
- sql - PostgreSQL:如何在函数中并行运行查询?
- javascript - 如何在 Vue js 中在线参考图片?
- java - 处理 100 万条记录的 Executor 框架