2014-02-26 250 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

我添加了一個演示來展示我的意思 –