0

我有 xml 文件,其中包含一些详细信息我想从中选择一些值我做了那个 javascript 但我不接近我的要求,我想从条件中选择值。

<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 回答