如果 ajax 刷新了绑定对象,则 .submit 不起作用

.submit doesn't work if the bind object was refreshed by ajax

本文关键字:submit 不起作用 对象 绑定 ajax 刷新 如果      更新时间:2023-09-26

我 AJAX化了注释系统,因此当单击Post Comment按钮时,将进行 ajax 调用而不是原始表单提交。在我使用 ajax 的评论提交按钮刷新页面之前,它工作正常。假设我只刷新包含帖子和评论以及按钮的div。之后,不会触发 ajax,而是使用原始提交方式。

提交表单的 javascript 看起来像

jQuery('document').ready(function($){
    var commentform=$('#commentform'); // find the comment form
    commentform.submit(function(){
//  $('#commentform').submit(function(){

我尝试使用$('#commentform')而不是没有帮助的变量。

我尝试在成功加载新帖子的 ajax 后再次分配注释表单变量。这也无济于事。

通过 ajax 加载帖子的 JavaScript 的一部分

var $ = jQuery.noConflict();
$(document).ready(function() { 
    $(".mhomepage_item").bind("click", function(){ //bind a click event on a class with name = mhomepage_item
    $.ajax({
            type: "POST",
            url: mhomepage.ajax_url,
            data: { 
                action: "get_post", 
                type: $(this).attr('type'), 
                current_post_id: $('#post_container').attr('current_post_id')
                },
            success: function(response) {
                response_from_json = JSON.parse(response);
                $('#content_container').html(response_from_json['html']);
                commentform=$('#commentform');
     }
    });
    // }
});

有人可以建议如何在通过 ajax 重新加载按钮后使表单提交按钮bind永久化吗?

尝试事件委托:

$(document).on("submit","#commentform",function(){
    // action to perform after submit intent
});
通过使用委托事件处理程序,

可以轻松处理动态创建的元素,而无需执行重新绑定事件处理程序之类的操作。

您还可以将事件绑定到调用函数时可用的body或最近的容器,以避免冒泡更多级别以document。您也可以在自己的情况下尝试此操作:

jQuery(document).ready(function($){
    $('#content_container').on("submit","#commentform",function(){
        // action to perform after submit intent
    });
});

文档

相应地: jQuery 绑定 在 AJAX 调用后单击链接

您必须在回调中绑定按钮以单击/提交事件success

你可以做:

success: function(response) {
      response_from_json = JSON.parse(response);
      $('#content_container').html(response_from_json['html']);
      commentform=$('#commentform');
      $('#commentform').bind("submit", function() { ... } );
}