使用jQuery - Cascading Select框从XML填充选择框

时间:2014-02-26 01:41:32

标签: javascript jquery html

我在弄清楚这个问题时遇到了一些麻烦。我需要有两个SELECT框,其中第一个选择框确定第二个选项的内容,如果选择第二个选项中的一个选项,将在新窗口(或新选项卡)中打开一个链接:< / p>

我的XML如下:

<?xml version="1.0" encoding="utf-8"?>
<countries>
  <country label="Australia">
    <store link="http://Link1a.com">Retailer 1a</store>
    <store link="http://Link1b.com">Retailer 1b</store>
    <store link="http://Link1c.com">Retailer 1c</store>
    <store link="http://Link1d.com">Retailer 1d</store>
    <store link="http://Link2a.com">Retailer 2a</store>
    <store link="http://Link2b.com">Retailer 2b</store>
    <store link="http://Link2c.com">Retailer 2c</store>
    <store link="http://Link2d.com">Retailer 2d</store>
  </country>
  <country label="Argentina">
    <store link="http://Link3a.com">Retailer 3a</store>
    <store link="http://Link3b.com">Retailer 3b</store>
    <store link="http://Link3c.com">Retailer 3c</store>
    <store link="http://Link3d.com">Retailer 3d</store>
    <store link="http://Link4a.com">Retailer 4a</store>
    <store link="http://Link4b.com">Retailer 4b</store>
    <store link="http://Link4c.com">Retailer 4c</store>
    <store link="http://Link4d.com">Retailer 4d</store>
  </country>
</countries>

我的脚本如下:

<script> 

$(document).ready(function() {
    var vendor_data; 
    $.get('links.xml', function(data) { 
        vendor_data = data; 
        var that = $('#countries'); 
        $('country', vendor_data).each(function() { 
            $('<option>').text($(this).attr('label')).appendTo(that);
        });
    }, 'xml');

    $('#countries').change(function() { 
        var val = $(this).val(); 
        var that = $('#store').empty(); 
        $('country', vendor_data).filter(function() { 
            return val == $(this).attr('label'); 
        }).find('store').each(function() {
            $('<option>').text($(this).text()).appendTo(that);  
        });
    });
});
</script>

HTML:

<form>
<select id="countries">
    <option value='0'>----------</option>
</select>
select id='store'>
    <option value='0'>----------</option>
</select>
</form>

目前,我可以使用数据填充第二个选择框,但是,我不知道如何将其转换为&#34;链接&#34;这样当它被选中时,它会打开一个新窗口,其中包含我希望访问者访问的页面的链接。

任何人都可以提供一些帮助或建议吗?

编辑:意思是说,更改&#34;链接&#34;在XML中以&#34;值&#34;对于<option>标记 例如。 <option value="linkfromxml"> Retailer 2d </option>

然后选择框以在新窗口中打开链接。

2 个答案:

答案 0 :(得分:0)

选择框无法显示带链接的选项,这将是无效的HTML。浏览器不知道如何处理标记。如果您正在寻找此类行为,则必须根据用户与选择框的互动来编写Javascript以更改document.location

E.g:

$('select').change(function (ev) {
    var val = $(this).val();
    document.location = '/?value=' + val;
});

答案 1 :(得分:0)

为什么不在第二个选择中添加更改侦听器?像。的东西。

$('#store').change(function() { 
   document.location = $(this).val();
});

<强>更新

Demo here

相关问题