Ztree创建带有复选框的树

需要增加的属性

check: {
    enable: true
}

封装的工具代码

function createTree(url, treeId) {
    var zTree; //用于保存创建的树节点
    var setting = { //设置
        check: {
            enable: true
        },
        view: {
            showLine: true, //显示辅助线
            dblClickExpand: true,
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pid",
                rootPId: 0
            }
        }
    };
    $.ajax({ //请求数据,创建树
        type: 'GET',
        url: url,
        dataType: "json", //返回的结果为json  
        success: function(data) {
            zTree = $.fn.zTree.init($(treeId), setting, data); //创建树
        },
        error: function(data) {
            alert("创建树失败!");
        }
    });
}

创建带有复选框的树

页面需要引入的元素
<link rel="stylesheet" href="../../css/zTreeStyle/zTreeStyle.css" />
<script type="text/javascript" src="../../js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../../js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="../../js/jquery.ztree.excheck.js"></script>
JavaScript调用代码
$(document).ready(function() {
    createTree("jsonData.json", "#treeDemo"); //创建
    $("#myButton").click(function() {
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = treeObj.getCheckedNodes(true);
        if(0 === nodes.length) {
            alert("请选择!");
            return;
        }
        var dataNodes = "";
        for(var i = 0; i < nodes.length; i++) {
            dataNodes += nodes[i].name + ",";
        }
        alert(dataNodes); //获取选中节点的值
    });
});
HTML的页面元素
<body>
<div style="margin-left: 50px;margin-top: 10px;">
    name:<input id="myData" type="text" placeholder="选中的内容" />
    <ul id="treeDemo" class="ztree" style="margin-top: 10px; width: 200px; height: 150px;">
    </ul>
    <button id="myButton" style="margin-top: 10px;">选中的元素</button>
</div>
</body>
使用的JSON数据
[
    {
        "id": 1,
        "pid": 0,
        "name": "pNode 1",
        "open": true,
        "attr": "id1"
    }, {
        "id": 11,
        "pid": 1,
        "name": "pNode 11",
        "attr": "id11"
    }, {
        "id": 111,
        "pid": 11,
        "name": "leaf node 111",
        "attr": "id111"
    }, {
        "id": 112,
        "pid": 11,
        "name": "leaf node 112",
        "attr": "id112"
    }, {
        "id": 12,
        "pid": 1,
        "name": "pNode 12",
        "attr": "id12"
    }, {
        "id": 2,
        "pid": 0,
        "name": "pNode 2",
        "attr": "id2"
    }, {
        "id": 21,
        "pid": 2,
        "name": "pNode 21",
        "open": true,
        "attr": "id21"
    }
]
生成的树

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值