简单树
/**
* 生成树结构
* @param {Object} obj 传入树的数据,格式为json
* [{"id":1035,"text":"车辆监测","children":[{"id":1036,"text":"实时监测","children":[]},{"id":1093,"text":"车辆查询","children":[]},{"id":1071,"text":"未识别车辆校对","children":[]}]},
*/
function cnznjtTree(o){
var s = "";
terr(o);
function terr(obj){
var obj1;
for(var i=0;i<obj.length;i++){
var o= obj[i];
if(obj[i].children &&obj[i].children !=[] && obj[i].children != '[]' && obj[i].children.length != 0 ){
s += '<div style="width:170px;"><label onclick="treeOpen(this)">' +
'<image onclick="treeOpen(this)" src="cnznjt_images/jia.png"></label>' +
'<input name="role.funId" type="checkbox" id="'+o.id+'" value="'+o.id+'" onclick="selAll(this)"/>'+o.text+'<div style="margin-left:10px;display:none;">';
obj1 = obj[i].children;
terr(obj1);
s += '</div></div>'
}else{
s += '<span style="cursor:pointer;margin-left:10px;width:170px;"><image src="cnznjt_images/bullet_blue.png"/><input type="checkbox" onclick="selAll(this)" name="role.funId" id="'+o.id+'" value="'+o.id+'"/>'+o.text+'</span><br/>'
}
}
}
return s;
}
/**
* 展开树
* @param {Object} treeDom 点击节点dom
*/
function treeOpen(treeDom){
var showImage=treeDom.parentNode.children[0];
if(treeDom.parentNode.children[2]){
var hideDiv=treeDom.parentNode.children[2].style;
if(hideDiv.display == 'none'){
hideDiv.display = 'block';
showImage.innerHTML= '<image src="cnznjt_images/jian.png">';
}else{
hideDiv.display = 'none';
showImage.innerHTML= '<image src="cnznjt_images/jia.png">';
}
}
}
/**
* 全选或者反选下级
* @param {Object} dom 上级dom
*/
function selAll(dom){
var dv = dom.parentNode;
var spanLength = $(dv.children[2]).contents("span").length;
var divLength = $(dv.children[2]).contents("div").length;
var ckeckedFlag = $(dom).attr("checked");
if(spanLength!=0||divLength!=0){
if(ckeckedFlag=='checked'){
$(dv.children[2]).find(':checkbox').attr("checked","checked");//选中上级,下级选中
}else{
$(dv.children[2]).find(':checkbox').attr("checked",false);//取消选中上级,取消下级选中
}
}
if(dv.parentNode){
parentCheck(dv);
}
}
/**
* 根据下级反选上级
* @param {Object} obj 选中dom
* @return {TypeName}
*/
function parentCheck(obj){//判断下级是否选中,递归判断上级选中情况
var i = 0,j = 0;
var checkObj = $(obj).find(":checkbox");
var checkLength = checkObj.length;
if(obj){
var _obj = obj.parentNode;
for(var l=0;l<checkLength;l++){
if($(checkObj[l]).attr("checked")=="checked"){
i++;
break;
}else{
j++;
}
}
if(i>0){
if($(_obj).children(":checkbox").attr("checked")){
return;
}
$(_obj).children(":checkbox").attr("checked",true);
}else if(checkLength==j){
$(_obj).children(":checkbox").attr("checked",false);
}else{
return;
}
parentCheck(_obj);
}
}