jquery带checkbox树控件及使用

文件包:jquery.checktree.rar

一.应用场景
权限树;需要多选包含父子级关系的分类等

二.树控件html示例
<ul class="tree" style="padding-left:120px;">
   <li rel='1'><input name="AbilityTags" type="checkbox" value="1" /><label>语言能力</label>
<ul>
   <li rel='11'><input name="AbilityTags" type="checkbox" value="11"/><label>阅读</label></li>
   <li rel='12'><input name="AbilityTags" type="checkbox" value="12"/><label>理解</label>
      <ul>
         <li rel='103'><input name="AbilityTags" type="checkbox" value="103"/><label>东</label></li>
      </ul>
   </li>
   <li rel='13'><input name="AbilityTags" type="checkbox" value="13"/><label>记忆</label></li>
   <li rel='15'><input name="AbilityTags" type="checkbox" value="15"/><label>英语启蒙</label></li>
   <li rel='88'><input name="AbilityTags" type="checkbox" value="88"/><label>高级</label></li>
   <li rel='99'><input name="AbilityTags" type="checkbox" value="99"/><label>2222</label></li>
   </ul></li>
   .....
</ul>

截图:

三、定义树控件函数和样式(样式文件见附件)
(function (jQuery) {
    jQuery.fn.checkTree = function (settings) {

        settings = jQuery.extend({
            /* Callbacks
            The callbacks should be functions that take one argument. The checkbox tree
            will return the jQuery wrapped LI element of the item that was checked/expanded.
            */
            onExpand: null,
            onCollapse: null,
            onCheck: null,
            onUnCheck: null,
            onHalfCheck: null,
            onLabelHoverOver: null,
            onLabelHoverOut: null,

            /* Valid choices: 'expand', 'check' */
            labelAction: "expand",

            // Debug (currently does nothing)
            debug: false
        }, settings);

        var $tree = this;

        $tree.find("li")
        // Hide all of the sub-trees
        .find("ul")
            .hide()
        .end()

        // Hide all checkbox inputs
        .find(":checkbox")
            .change(function () {
                // Fired when the children of this checkbox have changed.
                // Children can change the state of a parent based on what they do as a group.
                var $all = jQuery(this).siblings("ul").find(":checkbox");
                var $checked = $all.filter(":checked");

                // All children are checked
                if ($all.length == $checked.length) {
                    jQuery(this)
                        .attr("checked", "checked")
                        .siblings(".checkbox")
                            .removeClass("half_checked")
                            .addClass("checked")
                    ;
                    // Fire parent's onCheck callback
                    if (settings.onCheck) settings.onCheck(jQuery(this).parent());
                }

                // All children are unchecked
                else if ($checked.length == 0) {
                    jQuery(this)
                        .attr("checked", "")
                        .siblings(".checkbox")
                            .removeClass("checked")
                            .removeClass("half_checked")
                    ;
                    // Fire parent's onUnCheck callback
                    if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());
                }

                // Some children are checked, makes the parent in a half checked state.
                else {
                    // Fire parent's onHalfCheck callback only if it's going to change
                    if (settings.onHalfCheck && !jQuery(this).siblings(".checkbox").hasClass("half_checked"))
                        settings.onHalfCheck(jQuery(this).parent());

                    jQuery(this)
                        .attr("checked", "")
                        .siblings(".checkbox")
                            .removeClass("checked")
                            .addClass("half_checked")
                    ;
                }
            })
            .attr("checked", "")
            .hide()
        .end()


        .find("label")
        // Clicking the labels should expand the children
            .click(function () {
                var action = settings.labelAction;
                switch (settings.labelAction) {
                    case 'expand':
                        jQuery(this).siblings(".arrow").click();
                        break;
                    case 'check':
                        jQuery(this).siblings(".checkbox").click();
                        break;
                }
            })

        // Add a hover class to the labels when hovering
            .hover(
                function () {
                    jQuery(this).addClass("hover");
                    if (settings.onLabelHoverOver) settings.onLabelHoverOver(jQuery(this).parent());
                },
                function () {
                    jQuery(this).removeClass("hover");
                    if (settings.onLabelHoverOut) settings.onLabelHoverOut(jQuery(this).parent());
                }
            )
        .end()

        .each(function () {
            // Create the image for the arrow (to expand and collapse the hidden trees)
            var $arrow = jQuery('<div class="arrow"></div>');

            // If it has children:
            if (jQuery(this).is(":has(ul)")) {
                $arrow.addClass("collapsed"); // Should start collapsed

                // When you click the image, toggle the child list
                $arrow.click(function () {
                    jQuery(this).siblings("ul").toggle();

                    if (jQuery(this).hasClass("collapsed")) {
                        //toggled = settings.expandedarrow;
                        jQuery(this)
                            .addClass("expanded")
                            .removeClass("collapsed")
                        ;
                        if (settings.onExpand) settings.onExpand(jQuery(this).parent());
                    }
                    else {
                        //toggled = settings.collapsedarrow;
                        jQuery(this)
                            .addClass("collapsed")
                            .removeClass("expanded")
                        ;
                        if (settings.onCollapse) settings.onCollapse(jQuery(this).parent());
                    }
                });
            }

            // Create the image for the checkbox next to the label
            var $checkbox = jQuery('<div class="checkbox"></div>');

            // When you click the checkbox, it should do the checking/unchecking
            $checkbox.click(function () {
                // Make the current class checked
                jQuery(this)
                // if it's half checked, its now either checked or unchecked
                    .removeClass("half_checked")
                    .toggleClass("checked")

                // Send a click event to the checkbox to toggle it as well
                    .siblings(":checkbox").click()
                ;

                // Check/uncheck children depending on our status.
                if (jQuery(this).hasClass("checked")) {
                    // Fire the check callback for this parent
                    if (settings.onCheck) settings.onCheck(jQuery(this).parent());

                    jQuery(this).siblings("ul").find(".checkbox").not(".checked")
                        .removeClass("half_checked")
                        .addClass("checked")
                        .each(function () {
                            if (settings.onCheck) settings.onCheck(jQuery(this).parent());
                        })
                        .siblings(":checkbox")
                            .attr("checked", "checked")
                    ;
                }
                else {
                    // Fire the uncheck callback for this parent
                    if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());

                    jQuery(this).siblings("ul").find(".checkbox").filter(".checked")
                        .removeClass("half_checked")
                        .removeClass("checked")
                        .each(function () {
                            if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());
                        })
                        .siblings(":checkbox")
                            .attr("checked", "")
                    ;
                }
                // Tell our parent checkbox that we've changed
                jQuery(this).parents("ul").siblings(":checkbox").change();
            });

            // Prepend the arrow and checkbox images to the front of the LI
            jQuery(this)
                .prepend($checkbox)
                .prepend($arrow)
            ;
        })
    ;

        return $tree;
    };
})(jQuery);

四、使用说明
1.可获取当下展开节点、收起的节点、选中的节点、取消选中节点和子节点被部分选中的父节点的text和value值,函数分别为:onExpand、onCollapse、onCheck、onUnCheck

、onHalfCheck
$(document).ready(function () {
            $("ul.tree").checkTree({
            /*
            // You can add callbacks to the expand, collapse, check, uncheck, and  halfcheck
            // events of the tree. The element you use as the argument is the LI element of
            // the object that fired the event.
            onExpand: function (el) {
            console.log("expanded ", el.find("label:first").text());
     //ToDo
            },
            onCollapse: function (el) {
            console.log("collapsed ", el.find("label:first").text());
     //ToDo
            },
            onCheck: function (el) {
            console.log("checked ", el.find("label:first").text());
     //ToDo
            },
            onUnCheck: function (el) {
            console.log("un checked ", el.find("label:first").text());
     //ToDo
            },
            onHalfCheck: function (el) {
            console.log("half checked ", el.find("label:first").text());
     //ToDo
            }*/
            /*
            // You can set the labelAction variable to either "check" or "expand"
            // to change what happens when you click on the label item.
            // The default is expand, which expands the tree. Check will toggle
            // the checked state of the items.
            labelAction: "expand"
            */
            /*
            // You can also change what happens when you hover over a label (over and out)
            onLabelHoverOver: function(el) { alert("You hovered over " + el.text()); },
            onLabelHoverOut: function(el) { alert("You hovered out of " + el.text()); }
            */
        });
    });

2.可获取所有被选中节点、所有被选中且是最后一级的节点属性
    function getLastChooseItemValue() {
        var chooseDom = $("div.checked");
        var textArr = [];
        var valArr = [];
        for (var i = 0; i < chooseDom.length; i++) {
            var item = $(chooseDom[i]);
            var isLastItem = item.nextAll("ul").size() <= 0;
            if (isLastItem) {
                valArr.push(item.next("input").val());
                textArr.push(item.next("input").next("label:first").text());
            }
        }
    }

posted on 2012-11-15 16:50  cyz_393  阅读(877)  评论(0)    收藏  举报