2014-02-26 161 views
0

我在找出这个问题时遇到了一些麻烦。我需要两个选择框,第一个选择框决定第二个选择框的内容,如果选择第二个选择框中的一个,将在新窗口(或新选项卡)中打开链接:使用jQuery从XML中填充选择框 - 级联选择框

我的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> 

目前,我可以使用数据填充第二个选择框,但是我不知道如何将其转换为“链接”,以便在选中时打开一个新窗口,其中包含我希望访问者访问的页面的链接要去。

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

编辑:意思是说,将“XML”中的“链接”更改为<option>标签 的“值”。 <option value="linkfromxml"> Retailer 2d </option>

并获取选择框以在新窗口中打开链接。

+0

任何人有任何建议吗?我不知道如何编辑我的脚本来做我想做的事。如何将“价值”添加到选项标记中? – Keoki

回答

0

选择框无法显示包含链接的选项,这将是无效的HTML。浏览器不知道如何处理标记。如果你正在寻找这种行为,你必须编写Javascript来改变document.location的基础上用户与选择框的交互。

例如为:

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

为什么不加更改侦听到第二选择?就像是。

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

更新:

Demo here

+0

我不确定你的意思。它在我现有的脚本中如何工作? – Keoki

+0

我添加了一个演示来展示我的意思 –