在jQuery ajax响应之后重新绑定dymanically创建的表单
我是jQuery的新手,但在大多数情况下都理解它。 我的问题是,当我的ajax调用刷新整个div时,我所有动态创建的表单都不起作用。 如果您尝试提交它们,该事件将无法正常工作,只是尝试进行正常的表单提交。 我有所有其他项目,如使用.live()绑定的链接似乎工作得很好。 只是表格死了。 如何在ajax调用后重新绑定动态创建的表单? 它们都具有formname_id的id。 我试图使用绑定但它不起作用如下。 任何帮助表示赞赏。
这是代码
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; });
无需循环遍历表单以绑定它们。 如果你可以使用委托代替现场这样做。
为什么不覆盖正常表格提交:
function addNewitem() { $('#new_item_form').submit(function() { $.get("includes/ItemEdit.php", { newItem: true }, function(msg) { isNewItem = true; $("#new_item").hide(); $('#item_list').hide(); $("#item_edit").html( msg ); $("#item_edit").show(); editActiveEvent(); }); return false; }); }
不要忘记返回虚假。 或者做一个.preventDefault
我已经让这个工作在函数调用中添加事件并使用event.preventDefault(); 但当然只在FF。 在IE7中不起作用..
jQuery("form[id^='commentform_']").live('submit',function(event){ 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(); } }); event.preventDefault();});
但是IE7仍然试图对行动进行总结。 arrgggh ..我做错了什么?