2014-06-14 44 views
0

我有一個事件處理程序,當UL有子LI添加或刪除時運行。jQuery刪除/追加事件處理函數回調

在追加的情況下,回調是在元素追加後,這就是我想要的。

但是,在刪除的情況下,在元素被刪除之前執行回調。這意味着該回調只能訪問舊的UL,而不是元素被移除後的新UL。

我已經在回調中輸出了UL,事實上它是在刪除一個元素之前的UL。在元素被移除後,我希望回調與UL一起工作。人們可以在輸出列表的長度中看到這種證據。

http://jsfiddle.net/n9KYF/

HTML:

<ul id="myList"> 
    <li>a</li> 
    <li>b</li> 
    <li>c</li> 
</ul> 

<button id="removeButton">Remove Element</button> 
<button id="appendButton">Append Element</button> 

的Javascript:

$(document).ready(function() { 
    // removes the last element 
    $("#removeButton").click(function() { 
     var items = $("#myList").children(); 
     var lastIndex = items.length - 1; 
     if (lastIndex < 0) { 
      alert("nothing to remove"); 
     } else { 
      items.eq(lastIndex).remove(); 
     } 
    }); 

    // append a list item 
    $("#appendButton").click(function() { 
     var itemNumber = $("#myList").children().length; 
     var ch = String.fromCharCode(97 + itemNumber); 

     $("#myList").append("<li>" + ch + "</li>"); 
    }); 

    // event handler when the list is changed 
    // element not removed until AFTER this callback executed, how can 
    // suppress execution of this callback until after element removed 
    $(document.getElementById("myList")).bind("DOMNodeInserted DOMNodeRemoved", function() { 

     alert("Num Children : " + $(this).children().length); 

    }); 

回答

0

這是事實,DOMNodeRemoved被刪除之前被解僱。然而,這並不是一件壞事,因爲你可以得到從event.target中刪除的元素。

$(document.getElementById("myList")).bind("DOMNodeInserted DOMNodeRemoved", function(e) { 
    console.log(e.target); 
}); 
+0

所以我想要做的就是獲得該目標的父級,就好像目標已被刪除。讓我們在刪除之前調用parent_post父項,並在刪除之前調用parent_pre父項(這是我可以從回調中訪問的內容)。有什麼優雅的方式來獲得parent_post?除了做parent_pre「減去」的目標,獲得東西=== parent_post? –

0

DOMNodeRemoved在腳本準備移除項目之前觸發。在這裏閱讀官方介紹:

w3c.org(您需要向下滾動一點):

報價:

DOMNodeRemoved 當一個節點被從其父節點刪除觸發。 在將節點從樹中移除之前分派此事件。此事件的目標是被刪除的節點。

Bubbles: Yes 
    Cancelable: No 
    Context Info: relatedNode holds the parent node 

由於加工廠寫之前,我可以完成我的文章(;)),將event.target可以幫助你讓你刪除的項目。