JS多级分类联动选择


<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>JS多级分类联动选择</title>

<SCRIPT LANGUAGE='JavaScript'>

function myObject(){
    this.items = {};
    this.add = function(id,iArray){
        this.items[id] = iArray;
    }
    this.existed = function(id){
        var xx=typeof(this.items[id]);
        if( xx== 'undefined') 
            return false;
        return true;
    }
}


var s=['s1','s2','s3'];
var opt = ['选择一级','选择二级','选择三级'];

var obj = new myObject();
obj.add('0',['蔬菜','水果','杂粮']);

obj.add('0_0',['多叶','根茎']);
obj.add('0_0_0',['白菜','青菜','韭菜叶']);
obj.add('0_0_1',['韭菜根','萝卜','土豆']);

obj.add('0_1',['水果']);
obj.add('0_1_0',['葡萄','西瓜','菠萝']);

obj.add('0_2',['谷类','豆类']);
obj.add('0_2_0',['黑米','红米','糯米']);
obj.add('0_2_1',['豌豆','绿豆','红豆']);



function change(v){
    var str='0';
    for(i=0;i<v;i++){
        xx=document.getElementById(s[i]);
        str+=('_'+(xx.selectedIndex-1));
    }
    var ss=document.getElementById(s[v]);
    ss.length = 0;
    ss.options[0]=new Option(opt[v],opt[v]);
    var ii=document.getElementById(s[v-1]);
    createOptions(v,ss,ii,obj,str);
    
    ++v;
    if(v<s.length){
        change(v);
    }
}

function createOptions(v,ss,ii,obj,str){
    if(v && ii.selectedIndex>0 || !v){
        if(obj.existed(str)){
            ar = obj.items[str];
            for(i=0;i<ar.length;i++)
                ss.options[ss.length]=new Option(ar[i],ar[i]);
            if(v)
                ss.options[1].selected = true;
        }
    }
}




function setup(){
    for(i=0;i<s.length-1;i++){
        xx=document.getElementById(s[i]);
        xx.onchange=new Function('change('+(i+1)+')');
    }
    change(0);
}



</SCRIPT>

<body onload='setup();'>
JS多级分类联动选择:
  <select id='s1'><Option>一级分类</Option></select>
  <select id='s2'><Option>二级分类</Option></select>
  <select id='s3'><Option>三级分类</Option></select>
</body>







程序运行结果如下,点击这里亲自运行看看