2012-07-20 49 views
0

有刪除帖子的鏈接:重新綁定行動

<a id="post_232_destroy" class="postDestroy" rel="nofollow" data-remote="true" data-method="delete" data-confirm="Are you sure?" href="/someurl">Delete</a> 

的JavaScript(由coffescript編譯):

function() { 

    jQuery(function() { 
    return $("a.postDestroy").bind("ajax:success", function(event, data) { 
     $('#post_' + data.post_id).remove(); 
    }).bind("ajax:error", function() { 
     alert('Please try again'); 
    }); 
    }); 

}).call(this); 

我添加通過AJAX新後,所以綁定刪除按鈕丟失,爲每個最近添加的帖子。帖子被刪除,但ajax:成功沒有被調用,所以div不會被刪除。 我怎樣才能再次綁定它?

回答

0

在每次添加新帖子後,您可以解除綁定所有帖子,然後重新綁定。

$("a.postDestroy").unbind("ajax:success"); 
$("a.postDestroy").unbind("ajax:error"); 
$("a.postDestroy").bind("ajax:success", function(event, data) { 
    $('#post_' + data.post_id).remove(); 
}).bind("ajax:error", function() { 
    alert('Please try again'); 
}); 
}); 

編輯: 嘗試使用,而不是 「綁定」 jQuery的 「活」 的功能:

$("a.postDestroy").live("ajax:success", function(event, data) { 
    $('#post_' + data.post_id).remove(); 
}).live("ajax:error", function() { 
    alert('Please try again'); 
}); 
}); 
+0

這是一些解決方案,但它不是很乾。成功和錯誤的行動有點複雜,我只是修剪它們使代碼更具可讀性。 – Artur79 2012-07-20 13:13:22

+0

請參閱再次編輯的文章。 – 2012-07-24 12:13:14

+0

對不起,我不明白 – Artur79 2012-07-25 11:23:05