根据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}]}';
?>