标签:javascrpit js 级联下拉菜单 级联 下拉菜单
需要引入jQuery
级联下拉菜单JS-casdrop.js:
var div_cascade;
//数据格式示例
/*
[
{"id":1,"name":"数码","pid":0},
{"id":2,"name":"手机","pid":1},
{"id":3,"name":"笔记本","pid":1},
{"id":4,"name":"iphone","pid":2},
{"id":5,"name":"食物","pid":0},
{"id":6,"name":"土豆","pid":5},
{"id":7,"name":"thinkpad","pid":3}
]
*/
function casdrop_init(datas,div_cascade_l,id)//datas JSON数据,div_cascade_l jQuery选择器,根节点的id
{
div_cascade = div_cascade_l;
createChildrenDropBoxById(datas,id);
}
function createChildrenDropBoxById(datas,id)
{
var option_count = 0;
var select_data;
var select = $("<select></select>");
for(var i = 0;i < datas.length;i++)
{
if(datas[i].pid == id)
{
if(option_count == 0)
{
select_data = datas[i];
}
select.append("<option>"+datas[i].name+"</option>");
option_count++;
}
}
select.appendTo(div_cascade).change(function(){
var name = $(this).val();
var data = getByName(datas,name);
//var children = getChildrenById(datas,data.id);
deleteSelectionAfterMe($(this));
if(getChildrenById(datas,data.id).length != 0)
createChildrenDropBoxById(datas,data.id);
});
if(select_data && getChildrenById(datas,select_data.id).length != 0)
createChildrenDropBoxById(datas,select_data.id);
}
function deleteSelectionAfterMe($this)
{
$this.nextAll(‘select‘).remove();
}
function getByName(datas,name)
{
for(var i =0;i < datas.length;i++)
{
if(datas[i].name == name)
{
return datas[i];
}
}
}
function getChildrenById(datas,id)
{
var arr = [];
for(var i =0;i < datas.length;i++)
{
if(datas[i].pid == id)
{
arr.push(datas[i]);
}
}
return arr;
}
使用示例:
<div id=‘cascade‘ >
</div>
<script>
$.getJSON("ajaxtree",function(data){//AjaxCascadeDropBox
casdrop_init(data,$(‘#cascade‘),0);
})
</script>
效果截图:
标签:javascrpit js 级联下拉菜单 级联 下拉菜单
原文地址:http://blog.csdn.net/me10zyl/article/details/44998673