2010-05-02 14 views
1

我對jQuery有點新鮮但大部分理解它。我的問題是,當我刷新整個div的ajax調用完成時,我所有動態創建的表單都不起作用。如果您嘗試提交它們,則事件不會正常工作,只會嘗試執行正常的表單提交。我有所有其他項目,如使用.live()綁定的鏈接,這似乎很好。只是表格死亡。 如何在ajax調用之後重新綁定動態創建的表單?他們都有formname_id的id。我試圖使用綁定,但它不起作用如下。任何幫助表示讚賞。在jQuery ajax響應之後重新綁定動態創建的表單

下面是代碼

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

});

回答

4

嘗試做這樣的事情:

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而不是現場操作。

+0

很好的答案。 'live()'作爲附加事件的一種方式,它可以用於加載頁面後注入DOM的代碼。參見:http://api.jquery.com/live/ – artlung 2010-05-02 21:08:39

+1

如果你期望得到性能,'delegate()'是'live()'新的更好的更快版本。 – 2010-05-02 21:09:45

+0

@perter謝謝,但沒有奏效。它仍然會嘗試提交表單。 – 2010-05-02 21:15:14

0

你爲什麼不過乘坐普通表單提交:

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

    } 

不要忘了返回false。或做一個.preventDefault

0

我已經得到這個工作,在函數調用中添加事件,並使用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 ..我做錯了什麼?

+0

這可以正常使用event.preventDefault(); 但在IE 1.4.2中工作。使用1.4.1,直到它在下一個版本中固定。 http://dev.jquery.com/ticket/6359 – 2010-05-02 23:29:25

相關問題