簡體   English   中英

無法以正確方式在無序列表中顯示xml元素的內容

[英]Can't display content of xml elements in an unordered list in the proper way

我正在嘗試顯示我使用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元素中所有“注釋”標簽的內容顯示為無序列表。 我得到的結果是內容,但不是無序列表。 這是我正在嘗試的方法,它不起作用:

<!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已經加載)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM