首页 > 解决方案 > 为 KendoUI 网格列模板中的按钮添加 jQuery 单击事件

问题描述

所以,我有一些东西可以解决这个问题,但不幸的是,它需要onclick在列模板中处理我的 KendoUI 网格中的特定行。出于可维护性的目的,我想将其替换为 jQuery click 事件。棘手的事情之一是此事件需要Id单击按钮所在行的 ,但现在我更感兴趣的是获取该事件的代码。

这是我到目前为止的示例:

列模板

// columns is a Kendo.Mvc.UI.Fluent.GridColumnFactory of
// the type of the object I'm mapping to it

columns.Bound(p => p.SomeField).ClientTemplate(
    "<button type='button' class='btn btn-somefield'" + 
          "onclick='javascript:SomeAction(this, #=Id#);>" +
          "Some Button" +
    "</button>"
);

JavaScript 函数

function SomeAction(el, id){
    var reqUrl = 'someUrl' + '?id=' + id;

    $.ajax({
        type: 'GET',
        url: reqUrl,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (content) {
            console.log('request successful for id: ' + id);
        }
    });
}

我对 jQuery 实现有什么:

列模板

columns.Bound(p => p.SomeField).ClientTemplate(
    "<button type='button' class='btn btn-somefield'>" +
          "Some Button" +
    "</button>"
);

jQuery 函数

$('.btn-somefield').on('click', function(){
    // Here I have some unfinished code to get the Id and everything.
    // I'm not too concerned about figuring this out in this question, 
    // but suggestions are welcome

    // Otherwise it's the same body as the plain JS function
});

总结一下:现在,当单击按钮时,jQuery 事件没有被击中。我已经尝试了许多不同的迭代,例如:$(selector).on('click', function(){});$(selector).click(function(){});没有成功。

我担心一旦我真正到达事件处理程序后如何提取该行的 Id,但现在我只需要在单击按钮后点击该事件。

(此外,如果这对任何人有任何影响,整个项目都是一个 asp.net mvc 应用程序。)

标签: javascriptjqueryhtmlasp.net-mvckendo-ui

解决方案


尝试使用jQuery 事件委托。这允许您在生成网格按钮之前创建事件处理程序。然后要获取 ID,您可以使用dataItem() 方法获取网格行的 dataItem :

$(document).on('click', '.btn-somefield', function(e){
  var grid = $("#grid").data("kendoGrid");
  var dataItem = grid.dataItem($(this).closest('tr'));
  var ID = dataItem.Id;
});

推荐阅读