在項目中遇到最多的就是級聯菜單的實現。省級-市級-縣級等等。如果將這些數據放到數據庫中,每一次訪問數據都要鏈接數據庫。目前項目中的做法是select的每一次change事件都要查詢一次。我覺得此次操作有些多餘。先不說這些數據從哪裏得到,或者要不要放到緩存中,或者這些數據是不易改變,還是時常改變。我自我感覺有兩點不好:1、代碼與頁面的耦合性不好 2、會使頁面的速度變慢。
所以,我就用JQuery簡單實現了級聯菜單的實現。爲了避免有類似的問題,特將代碼附上,以便以後查看。共勉!
var json = {'id':'-1','name':'',parentId:'-2','children':[
{'id':'0','name':'河南',parentId:'-1',children:[
{'id':'01','name':'鄭州','parentId':'0','children':
[{'id':'011','name':'二七區',parentId:'-1',children:'-1'}]},
{'id':'02','name':'新鄉','parentId':'0','children':'-1'}]},
{'id':'1','name':'江蘇',parentId:'-1',children:[
{'id':'11','name':'江蘇1','parentId':'1','children':'-1'},
{'id':'12','name':'江蘇2','parentId':'1','children':'-1'}]}]};
var Settings = {
id:''
};
var DyCacadeSelect = {
init:function(id,json){
Settings.id = id;
DyCacadeSelect.recursion(json);
},
isChildren:function(note){
return note.children == '-1';
},
recursion:function(root){
if(DyCacadeSelect.isChildren(root)){
return ;
} else {
DyCacadeSelect.initSelect(root);
$.each(root.children,function(index,comment){
DyCacadeSelect.initOption(root,comment);
DyCacadeSelect.initSelectChange(root,comment);
});
}
},
initSelect:function(note){
$("#"+Settings.id).append("<select"+
" class='lSelect' id='"+note['parentId']+"'>"+
"<option value=''>--請選擇--</option></select>");
},
initOption:function(note,comment){
$("#"+note['parentId']).append("<option "+
"value='"+comment['id']+"'>"+comment['name']+"</option>");
},
initSelectChange:function(note,comment){
$("#"+note['parentId']).bind("change",function(){
if($("#"+note['parentId']).val()==''){
DyCacadeSelect.clearNextAllSelect(note);
}
if(comment['id'] == $("#"+note['parentId']).val()){
DyCacadeSelect.existNextSelectOperatorClear(note);
DyCacadeSelect.recursion(comment);
}
});
},
existNextSelectOperatorClear:function(note){
if(DyCacadeSelect.isExistNextSelect(note)){
DyCacadeSelect.clearNextAllSelect(note);
return true;
}
return false;
},
clearNextAllSelect:function(note){
$("#"+note['parentId']).nextAll('select').remove();
},
isExistNextSelect:function(note){
var selectLength = $("select[id="+note['parentId']+"]").length;
if(selectLength>0){return true;}
return false;
}
};
//調用方法
DyCacadeSelect.init("select",json);