2016-08-22 12 views
2

新しいコメントが追加されるたびにajax経由で読み込まれる部分的なビューを持つASP MVCアプリケーションがあります。JQueryクリックハンドラがAjaxページロード後に動作しない

しかし、jQueryのクリックハンドラーは、ajaxページのロード後には機能しなくなりました。 on()click()

<div id="comments"> 
    // Jquery links don't work after ajax page load? 
    <ul> 
     <li> 
      <div></div> 
      <a href="#" class="js-delete-comment" data-comment-id="@Model.comment.Id"> 
       <i class="fa fa-trash-o" aria-hidden="true"></i> Delete 
      </a> 
     </li> 
</div> 

@using (Ajax.BeginForm("Create", "Comments", null, new AjaxOptions 
{ 
     HttpMethod = "POST", 
     LoadingElementId = "create-post-wait", 
     InsertionMode = InsertionMode.Replace, 
     UpdateTargetId = "comments", 
     OnComplete = "AjaxCreatePostComplete()" 
}, new { enctype = "multipart/form-data" })) 
{ 

    @* form details *@ 

} 

私のjQuery

$(function() { 

     DeleteComment(); 

} 


var DeleteComment = function() { 

    if ($(".js-delete-comment").length === 0) { 
     return; 
    } 

    $(".js-delete-comment").click(function (e) { 
     var a = $(this); // "this" is the <a> 

     window.swal({ 
      title: "Confirm", 
      text: "Are you sure you want to delete this comment?", 
      type: "warning", 
      showCancelButton: true 
     }, 
     function() { 
      $.ajax({ 
       // do stuff 
      }) 
     }); 
     }); 
}; 


var AjaxCreatePostComplete = function() { 
     var createButton = $("#create-post-btn"); 
     if (createButton.length > 0) { 
      createButton.attr("disabled", false); 
     } 

}; 
+0

あなたのハンドラを定義する方法を教えてください –

+0

どのような 'クリック 'ハンドラですか? –

+0

新しいhtmlがDOMに挿入された後にクリックハンドラが動作しない場合、おそらく$(親).on()構文を使用してクリックイベントをバインドする必要があります。あなたはその側に任意のコードを表示havnt。 – Developer

答えて

3

使用jQueryのon()【選択の違いは、動的に追加された要素ためon()作品。

$(document).on('click','.js-delete-comment',function() { 
    //Add the logic for the click event here 
}); 
+0

+1しましたが、その理由を説明してください;) – DelightedD0D

関連する問題