我有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文件中丢失数据的一个例子。
<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值我希望按条件获得中国价格值。
答案 0 :(得分: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>