我有一個事件處理程序,當UL有子LI添加或刪除時運行。jQuery刪除/追加事件處理函數回調
在追加的情況下,回調是在元素追加後,這就是我想要的。
但是,在刪除的情況下,在元素被刪除之前執行回調。這意味着該回調只能訪問舊的UL,而不是元素被移除後的新UL。
我已經在回調中輸出了UL,事實上它是在刪除一個元素之前的UL。在元素被移除後,我希望回調與UL一起工作。人們可以在輸出列表的長度中看到這種證據。
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);
});
所以我想要做的就是獲得該目標的父級,就好像目標已被刪除。讓我們在刪除之前調用parent_post父項,並在刪除之前調用parent_pre父項(這是我可以從回調中訪問的內容)。有什麼優雅的方式來獲得parent_post?除了做parent_pre「減去」的目標,獲得東西=== parent_post? –