【问题标题】:Can't display content of xml elements in an unordered list in the proper way无法以正确的方式在无序列表中显示 xml 元素的内容
【发布时间】:2014-03-06 18:40:53
【问题描述】:

我正在尝试显示我使用 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>

你能说出原因吗?

【问题讨论】:

    标签: javascript xml html list


    【解决方案1】:

    附加.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 已加载)。

    【讨论】:

    • .innerHTML 不附加纯文本。它附加 HTML。因此,当您执行tag.innerHTML = '&lt;p&gt;'; 之类的操作时,您实际上是在附加&lt;p&gt;&lt;/p&gt;。我有一个JSFiddle 表明了这一点。我添加了一个&lt;p&gt; 和一个&lt;/p&gt;,但结果(在警告框中)非常不同。
    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多