【问题标题】:Add jQuery click event to button in KendoUI grid column template将 jQuery 单击事件添加到 Kendo UI 网格列模板中的按钮
【发布时间】:2019-11-15 17:57:57
【问题描述】:

所以,我有一些东西可以解决这个问题,但不幸的是,它需要列模板中的 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 应用程序。)

【问题讨论】:

  • 您的 jQuery 函数何时被调用?如果它在您的列内容呈现之前发生,那么它将找不到要附加到的按钮。
  • @J.Schmale 它在​​$(document).ready(function(){ }); 块内定义。否则它只是一个常规的点击事件。
  • 你能创建一个你的实现并分享的道场吗?
  • 可能会将您的 onclick 事件附加到网格的数据绑定事件中。这篇文章展示了一个例子:stackoverflow.com/questions/58881754/…
  • 在模板中添加 data-id 属性:stackoverflow.com/questions/5309926/…

标签: javascript jquery html asp.net-mvc kendo-ui


【解决方案1】:

尝试使用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;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 2019-07-26
    相关资源
    最近更新 更多