所以,我有一些方法可以解决这个问题,但不幸的是,它需要列模板中的 onclick
来处理 KendoUI 网格中的特定行。出于可维护性的目的,我想将其替换为 jQuery 单击事件。棘手的事情之一是此事件需要单击按钮的行的 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 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;
});
关于javascript - 将 jQuery 单击事件添加到 Kendo UI 网格列模板中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882376/