XML属性到HTML使用jquery选择值

时间:2012-03-19 15:05:29

标签: jquery xml

我是jquery的新手。我有一个XML文件,包含国家,州和城市的名称。 我想用jquery填充国家,州和城市的三个HTML。我已经成功地将国家名称转换为html。但我的问题是我无法将xml属性转换为值。

我的Xml文件如下:

<Locations>
  <Countries>
    <CName index='1'>Afghanistan</CName>
    <CName index='2'>Algeria</CName>
    <CName index='36'>India</CName>
  </Countries>
  <States>
    <SName cindex='36' sindex='1' stype='st'>Andhra Pradesh</SName>
    <SName cindex='36' sindex='2' stype='st'>Arunachal Pradesh</SName>
    <SName cindex='36' sindex='3' stype='st'>Assam</SName>
  </States>
  <Cities>
    <cindex>36</cindex>
    <cityname sindex='1' ctype='ct'>Anantpur</cityname>
    <cityname sindex='1' ctype='ct'>Guntakal</cityname>
    <cityname sindex='1' ctype='ct'>Guntur</cityname>
    <cityname sindex='1' ctype='mct'>Hydrabad/Secundrabad</cityname>
  </Cities>
</Locations>

我的HTML如下:

<select id="CounList" class="drsel01">// For Country
 </select>

<select id="StateList"></select> //For State

//适用于城市

我的JQuery代码如下:

<script type="text/javascript">
 $(document).ready(function() {
     var spl_data;      

     // Loading Country
     $.get('Locations.xml', function(data) {
         spl_data = data;
         var that = $('#CounList');
         $('CName', spl_data).each(function() {
             $('<option>').text($(this).text()).appendTo(that); //
             $('<option>').value($(this).attr('index')).appendTo(that);

         });
     }, 'xml');
 }); 

 I want to country name to be fill in <option> text and value of index attribute to be filled as <option> value.So that when i choose a country then related name of states or cities which belongs to country will be filled.

我已成功填写文字,但没有价值。

提前致谢。

2 个答案:

答案 0 :(得分:1)

没有名为value()的方法。如果要设置option元素的值,则应使用val()方法。即使在使用val()之后,您的代码也会创建2个选项元素并将它们附加到CountList。

试试这个

$('CName', spl_data).each(function() {
   $('<option />', { 
       text: $(this).text(),
       value: $(this).attr('index')
   }).appendTo(that);
});

工作演示 - http://jsfiddle.net/qQ2Xw/

答案 1 :(得分:0)

尝试

$('<option>').val($(this).attr('index')).appendTo(that);

而不是:

$('<option>').value($(this).attr('index')).appendTo(that);