2012-12-03 4 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>

I에서 내가 달성하고자하는 것이 무엇인지 분명히 밝혀지기 위해서 나는 유사한 질문에서 나온 답을 풀기 위해 노력하고 있었다 : 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")); 
     }); 
    } 
}); 

, 당신이 AJAX를 통해 XML을 끌어 경우, (와이 XML로 처리됩니다이 문서의 다른 종류의처럼 당신이 그것을 처리 할 수 ​​있는지 확인 일부주의 사항). 분명히 이것은 바닐라 자바 ​​스크립트로 수행 할 수 있지만 jQuery를 사용하면 더 쉽게 찾을 수 있습니다.

관련 문제