jQuery ajax响应后重新绑定动态创建的表单 [英] Rebind dymanically created forms after jQuery ajax response

查看:171
本文介绍了jQuery ajax响应后重新绑定动态创建的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手,但在大多数情况下都了解它.我的问题是,当刷新整个div的ajax调用完成时,我所有动态创建的表单都无法正常工作.如果您尝试提交它们,则该事件将无法正常运行,而只是尝试进行常规表单提交.我还有其他所有项目,例如使用.live()绑定的链接,它们似乎工作得很好.只是表格死亡. 在ajax调用之后,如何重新绑定动态创建的表单?它们都具有formname_id的ID.我尝试使用绑定,但如下所示无法正常工作.感谢您的帮助.

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies. How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.

这是代码

jQuery(document).ready(function(){   
jQuery("form[id^='commentform_']").each(function(){

    var id = parseInt(this.id.replace("commentform_", ""));         

    jQuery(this).bind('submit', function(e) {

        var action     = jQuery('#action_' + id).attr('value');
        var act_id    = ('1');  
            jQuery.ajax({
            type: "POST",
            url: "ajax/modify.php",
            data: "action="+ action +"& act_id="+ act_id,
            success: function(response){                
             jQuery('#CommentsContainer_' + id).html(response);
             jQuery('#commentform_' + id)[0].reset();
            }           
        });      
    return false;
    });
});             

});

推荐答案

尝试执行以下操作:

jQuery("form[id^='commentform_']").live('submit',function(){
    var id = parseInt(this.id.replace("commentform_", ""));
    var action = jQuery('#action_' + id).attr('value');
    var act_id = ('1');  
    jQuery.ajax({
        type: "POST",
        url: "ajax/modify.php",
        data: {"action": action, "act_id": act_id},
        success: function(response){                
            jQuery('#CommentsContainer_' + id).html(response);
            jQuery('#commentform_' + id)[0].reset();
        }           
    });      
    return false;
});

无需遍历表格即可绑定到表格.如果您可以使用 delegate 代替实时

No need to loop over the forms to bind to them. If you can use delegate instead of live do so.

这篇关于jQuery ajax响应后重新绑定动态创建的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆