2015-09-02 65 views
1

如何在加載延遲腳本後綁定點擊事件?在推遲初始化Kendo Grid後綁定點擊事件

我有一個Kendo網格(在剃刀)與延期初始化到期的性能問題。所以所有的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() 
) 

然後我有我想要的click事件綁定到<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

嘗試使用事件代表團

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元素沒有當事件是必然存在的。

+0

我將添加到答案代碼'event.stopPropagation()',所以傳播到span元素時id不是未定義的。 – Marlos