- 不说废话,直接demo,开箱即用
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<div id="xialakuang"></div>
<script>
var data = [{
"id": 10,
"name": '男装',
"children": [{
"id": 101,
"name": '正装'
},
{
"id": 102,
"name": 'T恤'
},
{
"id": 103,
"name": '裤衩'
}
]
},
{
"id": 20,
"name": '女装',
"children": [{
"id": 201,
"name": '短裙'
},
{
"id": 202,
"name": '连衣裙'
},
{
"id": 203,
"name": '裤子',
"children": [{
"id": 2031,
"name": '长裤'
},
{
"id": 2031,
"name": '九分裤'
},
{
"id": 2031,
"name": '七分裤'
}
]
},
]
},
{
"id": 30,
"name": '童装',
"children": [{
"id": 301,
"name": '帽子'
},
{
"id": 302,
"name": '套装',
"children": [{
"id": 3021,
"name": "0-3岁"
},
{
"id": 3021,
"name": "3-6岁"
},
{
"id": 3021,
"name": "6-9岁"
},
{
"id": 3021,
"name": "9-12岁"
}
]
},
{
"id": 303,
"name": '手套'
}
]
}
];
function sels(arr) {
var $sel = $("<select><option value='-1'>--请选择--</option></select>");
$(arr).each(function(index, num) {
var $opts = $("<option value=" + num.id + ">" + num.name + "</option>");
$sel.append($opts);
});
$sel.change(function() {
while (this != this.parentNode.lastChild) {
this.parentNode.removeChild(this.parentNode.lastChild);
}
var i = this.selectedIndex;
var cata = arr[i - 1];
if (i != 0 && cata.children) {
sels(cata.children)
}
});
$("#xialakuang").append($sel);
}
$(function() {
sels(data);
})
</script>
</body>
</html>
项目应用
需求:
- 有两个功能需要调用,需要小改动修改demo源码
- 上代码
// 无限极slelct [参数一:树结构,参数二,div的id]
function sels(data_tree,platformCategory) {
var $sel = $("<select class='form-control platform' style='width: 200px;'><option value='-1'>--请选择--</option></select>");
$(data_tree).each(function(index, num) {
var $opts = $("<option value=" + num.id + ">" + num.name + "</option>");
$sel.append($opts);
});
$sel.change(function() {
while (this != this.parentNode.lastChild) {
this.parentNode.removeChild(this.parentNode.lastChild);
}
var i = this.selectedIndex;
var cata = data_tree[i - 1];
if (i != 0 && cata.nodes) {
/***********递归调用的时候别忘记这里的参数哦**********************************/
sels(cata.nodes,platformCategory)
}else {
console.log("最后一个select");
/***********这里拿到最后选择的id**********************************/
console.log($sel.val());
}
});
console.log(platformCategory);
platformCategory.append($sel);
}
/* 平台分类、供应商分类*/
var platformCategory = $("#platformCategory");
sels(platform_category_tree_data,platformCategory);
var supplier_category = $("#supplier_category");
sels(supplier_category_tree_data,supplier_category);
- 完事
- 后端的json树结构数据,有时间再写出来博客。