html
<meta charset="utf-8">
<div class="unlimited" data="1" ajaxurl="#">
<select class="select_1" data="" name="bank">
<option value="">请选择</option>
<option value="1">四川省分行</option>
</select>
</div>
script
<script src="script/jquery-1.4.2.min.js"></script>
<script type="text/javascript">$(function () {
unlimited_select();
});
//Unlimited Select Functions
function unlimited_select(){
$('.unlimited').change(function () {
var num = parseInt($(this).attr('data'));
//找到发生改变的节点 并替换相应data值
for (var i = 1; i <= num; i++) {
var select_obj = $(".select_" + i);
var change_val = select_obj.val();
var select_val = select_obj.attr('data');
if (change_val != select_val) {
select_obj.attr('data', change_val); //替换data值
var current_num = i; //找到节点
break;
}
}
//当不是最后一个节点时,移除后面的节点,并获取name属性
if (current_num < num) {
for (var i = current_num + 1; i <= num; i++) {
var select_obj = $(".select_" + i);
if (i == num) {
var select_name = select_obj.attr('name');
}
select_obj.remove();
}
} else { //如果是当前最后节点,直接获取name属性,并移除该属性
var select_name = $(".select_" + num).attr('name');
//$(".select_" + num).removeAttr('name');
}
//如果选中的值不为空,则ajax请求后续节点
if (change_val == '') {
$(this).attr('data', current_num); //替换节点数data值
$(".select_" + current_num).attr('name', select_name);
} else {
var url = $(this).attr('ajaxurl');
//do ajax... return bank_data...
/*~~~~~~jsfiddle不方便做ajax请求操作,略过
var bank_data = null;
$.ajax({
url: url,
async: false,
type: 'POST',
data:{ },
success: function(msg){
bank_data = $.parseJSON(msg);
}
});
用下面替代~~~~~~*/
var bank_data = {
'4': 'AAA支行',
'5': 'BBB支行',
'6': 'CCC支行'
};
if (bank_data) { //有返回下一节点结果
$(this).attr('data', current_num + 1);
add_select( 'unlimited', select_name, current_num + 1, bank_data );
$(".select_" + current_num).removeAttr('name');
} else { //没有下一节点
$(this).attr('data', current_num);
}
}
});
}
function add_select( class_name, select_name, add_num, data){
var new_select = '<select class="select_'+add_num+'" data="" name="'+select_name+'"><option value="">请选择</option>';
for( key in data ){
new_select += '<option value="'+key+'">'+data[key]+'</option>';
}
new_select += '</select>';
$('.'+class_name).append(new_select);
}
</script>