[英]Populate Select box from XML with jQuery - Cascading Select boxes
我在弄清楚這個問題上遇到了一些麻煩。 我需要有兩個SELECT框,其中第一個選擇框確定第二個選擇框的內容,如果選擇了第二個選擇框,則將在新窗口(或新選項卡)中打開鏈接:
我的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>
並獲得選擇框以在新窗口中打開鏈接。
選擇框無法顯示帶有鏈接的選項,該鏈接將是無效的HTML。 瀏覽器不知道如何處理標記。 如果您正在尋找這種行為,則必須編寫Javascript來基於用戶與選擇框的交互來更改document.location
。
例如:
$('select').change(function (ev) {
var val = $(this).val();
document.location = '/?value=' + val;
});
為什么不只將更改偵聽器添加到第二個選擇項? 就像是。
$('#store').change(function() {
document.location = $(this).val();
});
更新:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.