2013-05-08 14 views
0

xml文件: -發現XML屬性值使用變量名稱

<countries> 
    <country code='af' phoneCode='93' name='Afghanistan' /> 
    <country code='al' phoneCode='355' name='Albania' /> 
    <country code='dz' phoneCode='213' name='Algeria' /> 
    <country code='ad' phoneCode='376' name='Andorra' /> 
    <country code='ao' phoneCode='244' name='Angola' /> 
    <country code='aq' phoneCode='672' name='Antarctica' /> 
    <country code='ar' phoneCode='54' name='Argentina' /> 
    <country code='am' phoneCode='374' name='Armenia' /> 
    <country code='aw' phoneCode='297' name='India' /> 
    <country code='au' phoneCode='61' name='Australia' /> 
</countries> 

這是我javscript AJAX: -

<script> 
    var getr=''; 
    var ind= "India"; 
    var getre; 
     function cli(){ 
      $.ajax({ 
       url: 'country_code.xml', 
       type:"get", 
       async: false, 
       success: function(xml) { 
         var result = $(xml).find("countries").each(function(){ 
          getr = $(this).find("country").attr('name'); 
          }); 
         alert(getr); 
       }, 
       error:function(){ 
        alert('err'); 
       } 
      }); 
     } 
    </script> 

在這裏,我要搜索屬性India
我嘗試以上,但它給我第一個Afghanistan
我該怎麼做。
謝謝。

+0

您正在迭代每個'country'節點並系統地覆蓋'getr'變量。第一個是阿富汗,超越循環的價值將是澳大利亞。我沒有得到你想要做的。如果'getr'的值是印度,你想返回印度..? – 2013-05-08 09:01:40

回答

2

也許像這樣的事情是你正在做的事情:
搜索國家條目與屬性名稱等於var ind。 在這個例子中,phoneCode將被返回。

success: function(xml) { 
       var result = $(xml).find("country").each(function(){ 
        if($(this).attr('name') == ind) { 
         getr = ind + " :" + $(this).attr('phoneCode') 
        } 
        }); 
       alert(getr); 
     },