How to access Kendo Grid's column menu only from outside the grid and add the filter option for specific columns in the column header

后端 未结 2 2043
感情败类
感情败类 2021-02-10 18:59

I am new to Kendo Grid and trying to use the columnMenu option. I need to access the column Menu function (only the ability to show/hide columns from a button outside the grid.

2条回答
  •  伪装坚强ぢ
    2021-02-10 19:25

    Not sure I got all requirements right, but something like this should work:

    JS:

    var grid = $("#grid").kendoGrid({
        dataSource: [{
            foo: "foo",
            bar: "bar"
        }],
        filterable: true,
        columnMenu: true
    }).getKendoGrid();
    
    function showMenu() {
        var offset = $(this).offset();
        var fieldName = $(this).data("field");
        var th = $(grid.thead).find("th[data-field='" + fieldName + "']");
    
        $(th).find(".k-header-column-menu:first").click();
        $(".k-column-menu").parent().css({
            top: offset.top + $(this).outerHeight(),
            left: offset.left
        });
    }
    
    $(document).on("click", ".grid-menu", showMenu);
    

    CSS:

    .k-header-column-menu {
        visibility: hidden
    }
    

    HTML:

    (demo)

    Another approach for just showing a menu with checkboxes while keeping the filter menu in the grid header:

    Grid:

    var grid = $("#grid").kendoGrid({
        dataSource: [{
            foo: "foo",
            bar: "bar"
        }],
        filterable: true,
        columnMenu: false
    }).getKendoGrid();
    

    Create menu entries from grid.columns:

    var ds = [];
    for (var i = 0, max = grid.columns.length; i < max; i++) {
        ds.push({
            encoded: false,
            text: ""
        });
    }
    

    Menu:

    $("#menu").kendoMenu({
        dataSource: [{
            text: "Menu",
            items: ds
        }],
        openOnClick: true,
        closeOnClick: false,
        open: function () {
            var selector;
            // deselect hidden columns
            $.each(grid.columns, function () {
                if (this.hidden) {
                    selector = "input[data-field='" + this.field + "']";
                    $(selector).prop("checked", false);
                }
            });
        },
        select: function (e) {
            // ignore click on top-level menu button
            if ($(e.item).parent().filter("div").length) return;
    
            var input = $(e.item).find("input.check");
            var field = $(input).data("field");
            if ($(input).is(":checked")) {
                grid.showColumn(field);
            } else {
                grid.hideColumn(field);
            }
        }
    });
    

    (demo)

提交回复
热议问题