在剑道网格延迟初始化后绑定点击事件

Bind click event after deferred initialization of Kendo Grid

本文关键字:绑定 事件 初始化 网格 延迟      更新时间:2023-09-26

如何在加载延迟脚本后绑定点击事件?

我有一个Kendo Grid(在Razor中)由于性能问题延迟初始化。所以所有的js脚本都包含在文档的末尾。

@(Html.Kendo().Grid<MyViewModel>()
    .Name("myGrid")
    .Columns(columns =>
    {
        columns.Bound(c => c.Name);
        columns.Bound(c => c.City);
        columns
            .Bound(c => c.Id)
            .Title("Commands")
            .Sortable(false)
            .Filterable(false)
            .ClientTemplate(
                "<a href='" + @Url.Action("Details", new { id = "#=Id#" }) + 
                    "' class='btn btn-success' title='Details'>" +
                    "<span class='glyphicon glyphicon-list'></span></a>" +
                "<a href='" + @Url.Action("Edit", new { id = "#=Id#" }) +
                    "' class='btn btn-info' title='Edit'>" +
                    "<span class='glyphicon glyphicon-pencil'></span></a>" +
                "<a href='''#' data-id='#=Id#' data-action='deactivate' " +
                    "class='btn btn-warning' title='Desactivate'>" +
                    "<span class='glyphicon glyphicon-remove-sign'></span></a>"
            );
    })
    .Pageable()
    .Sortable()
    .Filterable()
    .DataSource(ds => ds
        .Ajax()
        .Read(read => read.Action("ReadData", "MyController")).Sort(a => a.Add("Name")))
    .Deferred()
)

然后我在末尾有一个部分,我想将单击事件绑定到每个具有data-action='deactivate'属性的元素的<a>单击。问题是延迟初始化是在我的文档准备好之后执行的。

@section scripts {
    @Scripts.Render("~/bundles/kendo")
    @Html.Kendo().DeferredScripts()
    <script>
        $(document).ready(function () {
            $('[data-action="deactivate"]').click(function (event) {
                var id = $(event.target).attr('data-id');
                alert(id);
            });
        });
    </script>
}

尝试使用事件委派

http://learn.jquery.com/events/event-delegation/

$(document).on('click', '[data-action="deactivate"]'function (event) {
    var id = $(event.target).attr('data-id');
    alert(id);
});

这样,绑定事件时目标DOM元素就不必存在了。