在延迟初始化Kendo Grid之后绑定点击事件

时间:2015-09-02 17:43:37

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

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

我有一个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()
)

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

@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>
}

1 个答案:

答案 0 :(得分:1)

尝试使用事件委派

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元素。