我開始打造「向下鑽取」選擇元素(選擇基於您選擇前面的選項,篩選他們的選擇要素。下鑽使用JavaScript
是,我有以前從來沒有這樣做,我要尋找一個「最佳實踐」的方式來這種常見的情況,你能指出我的教程,或者提供一些示例代碼,我應該如何處理呢?
解決方案
我原創最終想到隱藏和顯示選項,但事實證明,這種方法不是跨瀏覽器兼容的。我遇到的最簡單的跨瀏覽器方法是創建原始選擇選項的副本,並在用戶選擇後替換選項。我寫了一個小的jQuery插件,使它更加可重用。
<select id="first">
<option value="1">Fruits</option>
<option value="2">Vegetables</option>
</select>
<select id="second">
<option> -- Select -- </option>
<!-- class is in the format of "parentId_parentValue" -->
<option class="first_1" value="1">Apple</option>
<option class="first_1" value="2">Orange</option>
<option class="first_1" value="3">Banana</option>
<option class="first_2" value="4">Carrot</option>
<option class="first_2" value="5">Broccoli</option>
<option class="first_2" value="6">Spinach</option>
</select>
<script type="text/javascript">
$.fn.drilldown = function(child) {
var $parent = this;
var parentId = $parent.attr('id');
var $child = $(child);
var childId = $child.attr('id');
var optionIdentifier = '.' + parentId + '_';
var selectedChildOption = $child.val();
var $childCopy = $('<select id='+parentId+childId+' />');
$childCopy.html($child.find('option')).hide().appendTo('body');
var refreshOptions = function(){
var selectedParentValue = $parent.val();
$child.html($childCopy.find(optionIdentifier+selectedParentValue).clone());
$child.prepend('<option value="0" selected="selected"> -- Select -- </option>');
};
refreshOptions();
$child.val(selectedChildOption);
$parent.change(function(){
refreshOptions();
$child.trigger('change').focus();
});
};
$(document).ready(function(){
$('#first').drilldown('#second');
});
</script>
這裏是一個jsFiddle表明,它的作品。
來獲取數據,這很容易,我可以在大約15分鐘內編寫代碼,但是我相信這裏有人已經準備好了,只需將它粘貼在這裏:)但如果幾個小時內你沒有得到答案,我會寫出來! – 2011-04-25 20:40:14