2012-12-03 147 views
2

動態下拉我有今天的問題與創建下拉列表:從XML創建

我有xml文件像這樣的結構是這樣的:

<resultset> 
    <row> 
    <field name="iso3166_2">AF</field> 
    <field name="country">AFGHANISTAN</field> 
    <field name="fixed">1.000</field> 
    <field name="mobile">1.300</field> 
    </row> 
    <row> 
    <field name="iso3166_2">US</field> 
    <field name="country">ALASKA</field> 
    <field name="fixed">0.100</field> 
    <field name="mobile">0.100</field> 
    </row> 
</resultset> 

而且我想創建掇列表中包含國家名稱(取自這些字段:<field name="country">...</field>)。

在addtion,從這個下拉菜單中選擇國家後,我想從在這種跨度的選擇country相同row集展示從fixedmobile變量:

<span id="mobile"><!-- mobile value --></span><span id="fixed"><!-- fixed value --></span>

我希望它清楚我想實現什麼,我試圖用類似問題的答案來解決它:dynamic load data from xml to drop down box with jquery但它不適合我(我想我錯了)。請幫忙!

回答

1

像這樣的東西應該工作:

$.ajax({ 
    url: 'img/test.xml', 
    dataType: 'xml', // Make sure it knows to treat it as XML 
    success: function(xml) { 
     var rows = xml.childNodes[0].getElementsByTagName("row"), 
      // This assumes your <select> has id of "countries" 
      $dropdown = $("#countries"); 

     $(rows).each(function(index, row) { 
      var fields = row.getElementsByTagName("field"), 
       $option = $(document.createElement("option")); 

      $(fields).each(function(index, field) { 
       var name = field.getAttribute("name"), 
        // A special way to get the text contents of an XML node 
        value = $(field).contents()[0].wholeText; 

       // If it's the "country" field, just stick it in the option 
       if (name == "country") { 
        $option.text(value); 
       } else { 
        // If it's anything else, store it as extra data 
        $option.data(name, value); 
       } 
      }); 

      $dropdown.append($option); 
     }); 

     // Whenever you change which option is selected 
     $dropdown.change(function() { 
      $option = $dropdown.find(":selected"); 

      // Fill in the spans using the extra data you saved 
      $("#fixed").text($option.data("fixed")); 
      $("#mobile").text($option.data("mobile")); 
     }); 
    } 
}); 

總之,如果你在你的XML通過AJAX拉,確保它當作XML,然後就像它的任何其他類型的文檔,你可以把它(用一些警告)。很明顯,這可以用vanilla JavaScript來完成,但我發現使用jQuery更容易。