工作中经常使用这个js自定义多级联动下拉菜单,实用方便
尤其当需要把将数据库中的层级数据转换为树形结构时,还有就是根据条件动态添加减少菜单时
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js自定义多级联动下拉菜单</title>
<script type="text/javascript">
var gt = function (id) {
return "string" == typeof id ? document.getElementById(id) : id;
};
function addEventHandler(oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = fnHandler;
}
};
function Each(arrList, fun){
for (var i = 0, len = arrList.length; i < len; i++) { fun(arrList[i], i); }
};
function GetOption(val, txt) {
var op = document.createElement("OPTION");
op.value = val; op.innerHTML = txt;
return op;
};
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
var CascadeSelect = Class.create();
CascadeSelect.prototype = {
//select集合,菜单对象
initialize: function(arrSelects, arrMenu, options) {
if(arrSelects.length <= 0 || arrMenu.lenght <= 0) return;//菜单对象
var oThis = this;
this.Selects = [];//select集合
this.Menu = arrMenu;//菜单对象
this.SetOptions(options);
this.Default = this.options.Default || [];
this.ShowEmpty = !!this.options.ShowEmpty;
this.EmptyText = this.options.EmptyText.toString();
//设置Selects集合和change事件
Each(arrSelects, function(o, i){
addEventHandler((oThis.Selects[i] = gt(o)), "change", function(){ oThis.Set(i); });
});
this.ReSet();
},
//设置默认属性
SetOptions: function(options) {
this.options = { //默认值
Default: [], //默认值(按顺序)
ShowEmpty: false, //是否显示空值(位于第一个)
EmptyText: "请选择" //空值显示文本(ShowEmpty为true时有效)
};
Object.extend(this.options, options || {});
},
//初始化select
ReSet: function() {
this.SetSelect(this.Selects[0], this.Menu, this.Default.shift());
this.Set(0);
},
//全部select设置
Set: function(index) {
var menu = this.Menu
//第一个select不需要处理所以从1开始
for(var i=1, len = this.Selects.length; i < len; i++){
if(menu.length > 0){
//获取菜单
var v