我正在尝试显示我使用 javascript 从 xml 文件加载的特定元素的内容,但它不起作用。 这是我的 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<book><title>Alice in Wonderland</title>
<author>Lewis Carroll</author>
<year>1866</year>
<comment> Alice falls down a rabbit hole into a fantasy world </comment>
<comment> Considered to be one of the best examples of the literary nonsense genre </comment>
<comment> Novel written by English author Charles Lutwidge Dodgson </comment>
</book>
我想使用 javascript 将 div 元素中所有“comment”标签的内容显示为无序列表。 我得到的结果是内容,但不是无序列表。 这是我正在尝试的方法,但它不起作用:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function loadXMLDoc(doc) {
if (window.XMLHttpRequest){
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("GET",doc,false);
request.send("");
return request.responseXML;
}
function displayunordered(doc) {
xmlDoc = "";
xmlDoc = loadXMLDoc(doc);
comment = xmlDoc.getElementsByTagName("comment");
document.getElementById('unordered').innerHTML = "<ul>";//insert opening ul tag
//pass from all comment elements
for(var i = 0 ; i < comment.length; i++){
var com = comment[i].childNodes[0].nodeValue;
document.getElementById('unordered').innerHTML += "<li>" + com;
document.getElementById('unordered').innerHTML += "</li>";
}
document.getElementById('unordered').innerHTML += "</ul>"; //insert closing ul tag
}//end of function displayunordered
</script>
</head>
<body>
<!-- div to display the result -->
<div id="unordered"> comments elements</div>
<a href="#" class="button" onclick="displayunordered('one-book.xml')">Show comments elements unordered</a>
</body>
</html>
你能说出原因吗?
最佳答案
附加.innerHTML
你正在做的方式是行不通的。您应该附加到一个临时变量,然后将该临时变量分配给 .innerHTML
。
var html = "<ul>";
for(var i = 0 ; i < comment.length;i++){
var com = comment[i].childNodes[0].nodeValue;
html += "<li>" + com;
html += "</li>";
}
html += "</ul>";
document.getElementById('unordered').innerHTML = html;
这是一个 JSFiddle该部分的(假设 XML 已经加载)。
关于javascript - 无法以正确的方式在无序列表中显示 xml 元素的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233181/