参考文章:EasyUI treegrid级联勾选或深度级联勾选扩展:两种扩展
在此参考文章的基础上进行扩展:判断子节点是否全选,若全选了,则勾选父节点,否则不勾选
(function ($) {
/**
* 扩展树表格级联勾选方法:
* @param {Object} container
* @param {Object} options
* @return {TypeName}
*/
$.extend($.fn.treegrid.methods, {
/**
* 级联选择
* @param {Object} target
* @param {Object} param
* id:勾选的节点ID
* deepCascade: 是否深度级联
* @return {TypeName}
*/
cascadeCheck: function (target, param) {
var opts = $.data(target[0], "treegrid").options;
if (opts.singleSelect)
return;
var idField = opts.idField; // 这里的idField其实就是API里方法的id参数
var status = false; // 用来标记当前节点的状态,true:勾选,false:未勾选
var selectNodes = $(target).treegrid('getSelections'); //获取当前选中项
for (var i = 0; i < selectNodes.length; i++) {
var selectid = selectNodes[i][idField];
// 若当前传入的id存在于已经勾选的项目中, 则状态为已勾选
if (param.id == selectid) {
status = true;
}
}
selectChildren(target[0], param.id, idField, param.deepCascade, status);
selectParent(target[0], param.id, idField, status); // 级联选择父节点
/**
* 级联选择子节点
* @param {Object} target
* @param {Object} id 节点ID
* @param {Object} deepCascade 是否深度级联
* @param {Object} status 节点状态,true:勾选,false:未勾选
* @return {TypeName}
*/
function selectChildren(target, id, idField, deepCascade, status) {
// 深度级联时先展开节点
if (!status && deepCascade) {
$(target).treegrid('expand', id);
}
// 根据ID获取下层孩子节点
var children = $(target).treegrid('getChildren', id);
for (var i = 0; i < children.length; i++) {
var childId = children[i][idField];
if (status) {
$(target).treegrid('select', childId);
} else {
$(target).treegrid('unselect', childId);
}
selectChildren(target, childId, idField, deepCascade, status); //递归选择子节点
}
}
/**
* 级联选择父节点
* @param {Object} target
* @param {Object} id 节点ID
* @param {Object} status 节点状态,true:勾选,false:未勾选
* @return {TypeName}
*/
function selectParent(target, id, idField, status) {
var parent = $(target).treegrid('getParent', id);
if (parent) {
var parentId = parent[idField];
if (status) {
if (checkAllSelect(parentId)) {
$(target).treegrid('select', parentId);
}
} else {
$(target).treegrid('unselect', parentId);
}
selectParent(target, parentId, idField, status);
}
}
/**
* 判断子节点是否全部选中
*/
function checkAllSelect(parentId) {
var flag = true
, childcodes = []
, selectNodesList = {};;
childcodes = $(target).treegrid('getChildren', parentId);
// 选中的记录
selectNodes = $(target).treegrid('getSelections');
for (var i = 0; i < selectNodes.length; i++) {
var selectid = selectNodes[i][idField];
selectNodesList[selectid] = selectNodes[i];
}
// 判断子节点是否都已经选择了,只要有一个没有选择的,该父节点都要去除选择
for (var i = 0, len = childcodes.length; i < len; i++) {
var childid = childcodes[i][idField];
if (!selectNodesList.hasOwnProperty(childid)) { // 若存在子节点没有勾选的,则将该元素移除
flag = false;
break;
}
}
return flag;
}
}
});
}(jQuery));
网友评论