繁体   English   中英

使用JavaScript解析xml文件时,如何查找HTML5的“数据”属性?

[英]How do I look up the HTML5 'data' attribute when parsing an xml file using Javascript?

这是我的代码。 我正在尝试提取“数据”属性,并将其放入ID为“ question”的末尾的div中。 我对JS还是很陌生,并且知道必须做一些非常基本的事情,这是怎么回事?

<!DOCTYPE HTML>

<html>
 <head>
  <script language="javascript" type="text/javascript">

 function display() {

  var base = document.getElementById("output");
  var CompleteSuggestion = base.getElementsByTagName("CompleteSuggestion")[1];
  var suggest = CompleteSuggestion.getElementsByTagName("suggest")[0];
  var question = suggest.getAttribute("data")[0].firstChild.data;



  document.getAttribute("data").innerHTML = question;


 }


  </script>

 </head>
 <body onload="display()">

 <xml id="output" style="display: none;">

        <CompleteSuggestion>
        <suggest data="hello">
      </CompleteSuggestion> 


 </xml>

<div class="question" id="question"></div>

 </body>
</html>

这是从xml文件获取属性的更好方法

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>

//use ajax to grab the xml file
//I had an xml file named your.xml in the same directory as this script
$.ajax({
    type: "GET",
    url: "your.xml",
    dataType: "xml",
    success: function (xml) {

        //when the file has loaded via the ajax request loop over each suggestion element
        $(xml).find('suggestion').each(function() {

            //get the value of the first attribute (data), from this suggestion row
            console.log( this.attributes[0].value );
        });
    }
});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM