jqGrid失款不可多得的輕量級前端框架,需求的需要,使用了jqGrid的treeGrid做數據展示,其對異步展開節點支持的很好,用起來很省心。
使用中有對樹形的數據多選的需求,需要選擇一個節點,同時選擇其所有子節點;查看了API,發現treeGrid不支持,還是自己動手來完成,廢話不多說,先上個圖:
下面是關鍵代碼:
colNames:['id',nameFormat,'type']
colModel:[
{name:"id","index":"id",key:true,hidden:true},
{name:"name",label:"name", width:160,resizable: true,sortable:false,formatter:showName},
//....
]
nameFormat在“名稱”列頭添加了的複選框,showName是在名稱前加複選框
var nameFormat= '<label>'+
'<input type="checkbox" class="ace" id="chxCheckAll">'+
'<span class="lbl align-top" >名稱</span>'+
'</label>';
function showName( cellvalue, options, cell ) {
var rowId = cell.id;
var checkbox = '<label >'+
'<input type="checkbox" id="chx'+rowId+'" class="ace" value="'+rowId+'" onclick="clickCheckbox('+rowId+', this);" />'+
'<span class="lbl align-top" ></span>'+
cell.name +
'</label>';
return checkbox ;
}
複選框的勾選觸發clickCheckbox,勾選子節點和父節點需要用到getNodeChildren和getNodeParent方法
//全選/全不選
$("#chxCheckAll").on('click', function(){
$("input[id^='chx']").each(function(){
$(this).prop("checked", $("#chxCheckAll").is(':checked'));
});
});
//checkbox事件
clickCheckbox = function clickCheckbox(rowid, $this) {
checkChildren(rowid,$this);
if($($this).is(':checked')){
checkParent(rowid, $this);
}else{
$("#chxCheckAll").prop("checked",false);
}
};
//遞歸選中子節點
function checkChildren(rowid,$this){
var records = $(grid_selector).jqGrid('getNodeChildren',$(grid_selector).jqGrid("getLocalRow", rowid));
if(records.length>0){
for (var i=0;i<records.length;i++){
var cb = $("#chx"+records[i].id);
cb.prop("checked", $($this).is(':checked'));
checkChildren(records[i].id,cb);
}
}
}
//遞歸選中父節點
function checkParent(rowid, $this){
var parent = $(grid_selector).jqGrid('getNodeParent',$(grid_selector).jqGrid("getLocalRow", rowid));
if(parent){
var cb = $("#chx"+parent.id);
cb.prop("checked", $($this).is(':checked'));
checkParent(parent.id,cb);
}
}
需要注意的是獲取當前record這裏需要使用getLocalRow,若使用getRowDate或getInd會獲取不到子節點或父節點
功能完成。希望此文對有同樣需求的朋友有所幫助。