2013-05-16 51 views
2

我目前正在對相當簡單的東西進行測試。在我的項目中,您可以通過表單添加一個listitem,並立即在更新列表中刪除它。在文件的開頭我綁定刪除單擊處理程序:Ajax回調後未檢測到點擊

$(".delete").bind("click", this.deleteListitem); 

我認爲與類的所有元素「刪除」之前或Ajax調用之後被去除。所以當我添加一個新的listitem類「刪除」,我嘗試點擊它,但它不會進入函數。舊的項目。

刪除功能:

PanelRoadtrip.prototype.deleteListitem = function(e) 
{ 
    console.log("click"); 
    e.preventDefault(); 

    this.listId = $(event.currentTarget).parent().parent().attr("id"); 
    this.listItemValue = $(event.currentTarget).parent().text().split(" delete")[0]; 
    $.ajax({ 
     type: "delete", 
     url: Util.api + "/roadtrip/delete/" + this.tripId + "/" + this.listId + "/" + this.listItemValue, 
     dataType: "json" 
    }); 
    //item verwijderen 
    $(event.currentTarget).parent().remove(); 
}; 

是否有人對這個問題的簡單解決方案,搜索#2,但沒有發現任何作品。

在此先感謝

回答

4

您需要使用on(),而不是bind()變化:

$(".delete").bind("click", this.deleteListitem); 

$(document).on("click",".delete", this.deleteListitem); 

(其中document.delete上負載時的DOM父元素

Docs for on() are here。閱讀授權事件部分:

委託事件的優點是它們可以處理來自稍後添加到文檔中的後代元素的事件。通過選擇在委託事件處理程序附加時保證出現的元素,可以使用委派事件避免需要頻繁附加和刪除事件處理程序

+1

謝謝你的回答,我今天學到了一課:) – user2381011

1

可以使用.on()

http://api.jquery.com/on/

而不是

$(".delete").bind("click", this.deleteListitem); 

使用

$(document).on("click", ".delete" this.deleteListitem); 
//Instead of document use a parent container that exists in DOM at any give time. 
使用委派事件處理程序動態創建的內容

您新添加的類爲.delete的元素沒有默認綁定的事件,所以這種方法是將事件附加到文檔或父容器,併爲現在或稍後添加到DOM的類.delete的元素委派事件。

0

由於元素不存在DOM準備好了,你應該綁定它.on()

$(document).on("click", ".delete", this.deleteListitem);