jquery - 使用 jquery 将 XML 属性转为 HTML 选择值

标签 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.

我已成功填充文本,但未填充值。

提前致谢。

最佳答案

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

试试这个

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

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

关于jquery - 使用 jquery 将 XML 属性转为 HTML 选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772577/

相关文章:

jquery - 需要覆盖 CSS 背景色

jquery - <div> 在 fadeIn 之前短暂出现 - jQuery

xml - 如何在 Go 中使用 XPath 从 XML 中获取值

c# - .NET Xml 反序列化,xsi :type attribute 的问题/错误

c# - LINQ to XML XElement 节点

javascript - 在引导弹出窗口中添加此共享按钮

javascript - 类似于 JavaScript 对象的合并/连接方法.. 不扩展

jquery验证: How to figure out the form associated with a validator?

java - 如何使用 Java 替换位于特定标记内的 XML 标记的 CDATA 内的值

sql-server - 为什么将数据以 XML 格式存储在 SQL Server 中的各个列上?