首页 文章

如何以编程方式创建新行并将该行置于Kendo网格中的编辑模式

提问于
浏览
6

在我的Kendo网格中,我试图将“创建新项目”按钮放在命令列的 Headers ( Headers )而不是工具栏中 . 这是我的网格定义的一部分:

var grid = $("#grid").kendoGrid({
columns: [{ command: { name: "edit", title: "Edit", text: { edit: "", cancel: "", update: "" } },
headerTemplate: "<a onclick ='NewItemClick()' class='k-button k-button-icontext k-create-alert' id='new-item-button' title='Click to add a new item'><div>New Item</div></a>"},

我的问题是:如何创建一个新行并将该行置于'NewItemClick()'中的编辑模式

3 回答

  • 7

    当您尝试在模板定义本身中绑定click事件时,存在一些麻烦的范围问题 .

    相反,更容易为链接分配ID,然后再绑定click事件 . 请注意,我已经给它id = create .

    headerTemplate: "<a id='create' class='k-button k-button-icontext k-create-alert' id='new-item-button' title='Click to add a new item'><div>New Item</div></a>"
    

    然后在文档就绪,我绑定click事件:

    $("#create").click(function () {
        var grid = $("#grid").data("kendoGrid");
        if (grid) {
            //this logic creates a new item in the datasource/datagrid
            var dataSource = grid.dataSource;
            var total = dataSource.data().length;
            dataSource.insert(total, {});
            dataSource.page(dataSource.totalPages());
            grid.editRow(grid.tbody.children().last());
        }
    });
    

    上面的函数通过操作数据源在网格底部创建一个新行 . 然后它将新行视为"edit"行 . 创建新行的操作是从OnaBai的回答here借来的 .

    这是一个工作 jsfiddle ,希望它有所帮助 .

  • 2

    我想完成gisitgo的回答 . 如果您的数据源需要一些时间来更新,那么在调用 page(...) 时,网格的刷新将取消编辑器的弹出窗口 . 通过将对editRow的调用绑定到 "change" 事件来避免这种情况:

    var grid = $("#grid").data("kendoGrid");
    if (grid) {
      //this logic creates a new item in the datasource/datagrid
      var dataSource = grid.dataSource;
      var total = dataSource.data().length;
      dataSource.insert(total, {});
      dataSource.one("change", function () {
        grid.editRow(grid.tbody.children().last());
      });
      dataSource.page(dataSource.totalPages());
    }
    

    注意:如果您的网格已排序,这种方法会产生问题,因为新行不一定在最后

  • 0

    我发现如果您有多个页面可能会出现问题,例如插入的行未打开以进行编辑 . 这是一些基于复制行的当前索引的代码 .

    我们还基于UID编辑行以获得更高的准确性 .

    function cloneRow(e) {
        var grid = $("#grid").data("kendoGrid");
        var row = grid.select();
    
        if (row && row.length == 1) {
            var data = grid.dataItem(row);
    
            var indexInArray = $.map(grid.dataSource._data, function (obj, index)
            {
                if (obj.uid == data.uid)
                {
                    return index;
                }
            });
    
            var newRowDataItem = grid.dataSource.insert(indexInArray, {
                CustomerId: 0,
                CustomerName: null,                
                dirty: true
            });
            var newGridRow = grid.tbody.find("tr[data-uid='" + newRowDataItem.uid + "']");
            grid.select(newGridRow);
            grid.editRow(newGridRow);
            //grid.editRow($("table[role='grid'] tbody tr:eq(0)"));
        } else {
            alert("Please select a row");
        }
        return false;
    }
    

相关问题