【问题标题】:Bind click event after deferred initialization of Kendo Grid延迟初始化 Kendo Grid 后绑定点击事件
【发布时间】:2015-09-02 17:43:36
【问题描述】:

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

我有一个剑道网格(在 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' 属性的每个元素的 &lt;a&gt; 点击。问题是在我的文档准备好之后执行延迟初始化。

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

【问题讨论】:

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


    【解决方案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元素就不必存在了。

    【讨论】:

    • 我会在答案中添加代码event.stopPropagation(),以便在传播到 span 元素时不会未定义 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多