【问题标题】:.submit doesn't work if the bind object was refreshed by ajax如果绑定对象被 ajax 刷新,.submit 不起作用
【发布时间】:2013-10-21 00:06:13
【问题描述】:

AJAXified commenting system 所以当点击Post Comment 按钮时,会调用ajax 而不是原来的表单提交。在我使用 ajax 的评论提交按钮刷新页面之前,它工作正常。假设我只刷新了包含帖子和 cmets 以及按钮的 div。之后不再触发ajax,而是使用原始的提交方式。

提交表单的javascript看起来像

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

    commentform.submit(function(){
//  $('#commentform').submit(function(){

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

在成功加载新帖子的 ajax 之后,我尝试再次分配 commentform 变量。这也没有帮助。

通过 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');
     }
    });

    // }
});

有人可以建议如何使bind 形成提交按钮,即使在通过 ajax 重新加载按钮后也是如此?

【问题讨论】:

  • 任何与此相关的 HTML 都会很有帮助...

标签: javascript ajax wordpress jquery


【解决方案1】:

尝试事件委托:

$(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
    });
});

Documentation

【讨论】:

  • +1 我正要这样发布我的答案。请注意:.on() 需要 jQuery 1.7+
  • 第二个注意事项:您可以将$(document) 替换为$("body") 或表单最接近的父选择器。
  • @JFK:实际上,#content_container 就足够了。我认为
  • 两个例子都很好用。谢谢你。你能解释一下为什么它以前不起作用吗?我迷路了。
  • @Radek:您的代码使用直接事件处理程序。事件处理程序直接附加到您的#commentform,当您调用$('#content_container').html 时,您的 DOM 对象将被替换为没有事件处理程序的新对象。
【解决方案2】:

据此:jQuery binding click to a link after AJAX call

你必须在success回调中绑定一个按钮来点击/提交事件。

你可以这样做:

success: function(response) {
      response_from_json = JSON.parse(response);

      $('#content_container').html(response_from_json['html']);
      commentform=$('#commentform');

      $('#commentform').bind("submit", function() { ... } );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2013-07-27
    相关资源
    最近更新 更多