我有一个事件处理程序,当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? –