0

私はいくつかの詳細を含むxmlファイルを持っています.

<edata updated="2012:12:32.697" product_type_id="3" product_type="epack" headline="Gold Coast" destination="india" localised_destination="Gold Coast" headline_no_html="Gold Coast" price="372" />
<edata updated="2012:12:32.697" product_type_id="3" product_type="epack" headline="Gold Coast" destination="china" localised_destination="Gold Coast" headline_no_html="Gold Coast" price="450" />

これは、xml ファイル内のデータを失った例です。

ヘッダー部分の JavaScript

<script type="text/javascript">
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","edata.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
</script>

本体部分のコード

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
    var x=xmlDoc.getElementsByTagName("edata");
    document.write("<div>");
    document.write(x[0].getAttribute('price'));
    document.write("</div>");
  </script>
</div>

私のコードは最初の div で最初の edata 値を取得していることに注意してください。条件によって中国の価格値を取得したいと考えています。

4

1 に答える 1

1

これに「jquery」とタグ付けしたので、jqueryを使用していると思います(コード例はそれを暗示していませんが)。jQueryを使用すると、(jQuery.ajaxを使用してデータをより簡潔に取得してから...):

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
   $xml = $( xmlDoc ),
   $title = $xml
     .find( "edata[price]" ) //gets all nodes with a price
     .filter( function(i) {
         // filter out all the items that have a price less than 100
         return ( parseInt( this.attr("price") ) > 100 ) ? true : false;
     })
   ; 
  </script>
</div>

jQuery を使用したくない場合は、もちろんループを使用する必要があります。

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
    var x=xmlDoc.getElementsByTagName("edata");
    var i, l = x.length;
    var price;
    for( i = 0; i < l; i++ ){
      price = x[i].getAttribute( 'price' );
      if( typeof price !== "undefined" && parseInt( price ) > 100 ){
        document.write("<div>" + price + "</div>");
      }
    }
  </script>
</div>
于 2012-04-14T05:40:46.377 に答える