问题描述
- zTree如何只取子节点的id值
-
zTree如何只取子节点的id值,目前项目中不需要取父节点的值,如何取得所有的子节点的值?
解决方案
1.获取当前节点
2.用ztree的方法transformToArray()获取当前选中节点(含选中节点)的子节点对象集合。
3.遍历集合,取出需要的值。
function getChildNodes(treeNode) {
var childNodes = ztree.transformToArray(treeNode);
var nodes = new Array();
for(i = 0; i < childNodes.length; i++) {
nodes[i] = childNodes[i].id;
}
return nodes.join(",");
}
解决方案二:
判断节点的isParent属性,为true就是父节点,否则子节点,再获取值
var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getNodes();//获取所有节点 treeObj.getSelectedNodes();//获取选中的节点
for(var i=0,j=nodes.length;i<j;i++)
if(!nodes[i].isParent)alert('子节点:'+nodes[i].name)
解决方案三:
对所有节点遍历,,然后判断if(!node.isParent){console.log(node.id)}就可以了
解决方案四:
已经解决了,附上实例。。。感谢各位大神,还有一个问题,zTree怎么赋值呢?比如说我现在存在数据库的值是211,111,不通过JSON怎么赋值到ZTree呢?
<SCRIPT type="text/javascript">
<!--
var setting = {
check: {
enable: true
},
data: {
simpleData: {
enable: true
}
},
callback: {
onCheck:onCheck
}
};
var zNodes =[
{ id:1, pId:0, name:"随意勾选 1", open:true},
{ id:11, pId:1, name:"随意勾选 1-1", open:true},
{ id:111, pId:11, name:"随意勾选 1-1-1"},
{ id:112, pId:11, name:"随意勾选 1-1-2"},
{ id:12, pId:1, name:"随意勾选 1-2", open:true},
{ id:121, pId:12, name:"随意勾选 1-2-1"},
{ id:122, pId:12, name:"随意勾选 1-2-2"},
{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
{ id:21, pId:2, name:"随意勾选 2-1"},
{ id:22, pId:2, name:"随意勾选 2-2", open:true},
{ id:221, pId:22, name:"随意勾选 2-2-1", checked:true},
{ id:222, pId:22, name:"随意勾选 2-2-2"},
{ id:23, pId:2, name:"随意勾选 2-3"}
];
var code;
function setCheck() {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
py = $("#py").attr("checked")? "p":"",
sy = $("#sy").attr("checked")? "s":"",
pn = $("#pn").attr("checked")? "p":"",
sn = $("#sn").attr("checked")? "s":"",
type = { "Y":py + sy, "N":pn + sn};
zTree.setting.check.chkboxType = type;
showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
}
function showCode(str) {
if (!code) code = $("#code");
code.empty();
code.append("<li>"+str+"</li>");
}
$(document).ready(function(){
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
setCheck();
$("#py").bind("change", setCheck);
$("#sy").bind("change", setCheck);
$("#pn").bind("change", setCheck);
$("#sn").bind("change", setCheck);
});
function onCheck(e, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
nodes = zTree.getCheckedNodes(true),
v = "";
for (var i=0, l=nodes.length; i<l; i++) {
if(!nodes[i].isParent){
v += nodes[i].id + ",";
}
}
alert(v); //获取选中子节点的id值
//-->
</SCRIPT>
时间: 2024-10-04 01:19:40