关联选择 可以无限扩展

根据parentid来识别后面关联的选项

前端html的代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>无标题文档</title>
</head>

<body>
<div id="J_select_wrap">
</div>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
var select_list = [];
function select_change(e){
	var index = $(e).index();//索引,取第一个元素
	$('#J_select_wrap select:gt('+index+')').remove();//:gt 选择器选取 index 值高于指定数的元素
	get_child_option($(e).find('option:selected').val());//取到选中的值的val,即id
}
function get_child_option(num){
	var inner_option = '';
	for(var data_i in select_list){
		if(select_list[data_i].parentid == num){
			inner_option = inner_option + '<option value="'+select_list[data_i].id+'">'+select_list[data_i].name+'</option>';
		}
	}
	if(inner_option != ''){
		$('#J_select_wrap').append('<select οnchange="select_change(this)">'+inner_option+'</select>');
		var select_num = $('#J_select_wrap select').length;//取到select的个数
		get_child_option($('#J_select_wrap select').eq(select_num - 1).find('option:selected').val());//eq()函数的返回值为jQuery类型,返回封装了指定索引index处的元素的jQuery对象
	}
}
$.ajax({
	url:'list.php',
	type:'get',
	dataType:'json',
	success:function(data){
		select_list = data.data;
		get_child_option(1);
	},
	error:function(){
	}
});
</script>
</body>
</html>



数据的类型是有id,和parentid,以及name的类的数组

ajax请求的PHP数据,放在同目录下的list.php文件的代码

<?php
echo '{"code":1,"data":[{"id":1,"name":"july","parentid":0,"order":200},{"id":2,"name":"web","parentid":1,"order":200},{"id":5,"name":"test","parentid":1,"order":800},{"id":6,"name":"test2","parentid":5,"order":200},{"id":7,"name":"test22","parentid":5,"order":200},{"id":8,"name":"test31","parentid":6,"order":200}]}';
?>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值