向KendoUI网格列模板中的按钮添加jQuery click事件

问题描述 投票:0回答:1

所以,我为此有一些工作,但是不幸的是,它需要列模板中的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 Function

$('.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应用程序,如果这对任何人都有所不同。)

javascript jquery html asp.net-mvc kendo-ui
1个回答
2
投票

尝试使用jQuery event delegation。这使您可以在生成网格按钮之前创建事件处理程序。然后,要获取ID,可以使用dataItem() method

获取网格行的dataItem。
$(document).on('click', '.btn-somefield', function(e){
  var grid = $("#grid").data("kendoGrid");
  var dataItem = grid.dataItem($(this).closest('tr'));
  var ID = dataItem.Id;
});
© www.soinside.com 2019 - 2024. All rights reserved.