4

I'm removing an html element with .remove() method and at the same time for this element I have an event handler but it is not triggered. Why can that be? Here is the jsFiddle and code: HTML

<span id='del_span'>Delete</span><br>
<span id='to_del'>I'm going to be deleted</span>

JS

$('#del_span').click(function() {
    $('#to_del').remove();
});
$('#to_del').on('remove', function() {
    alert("I'm being deleted"); //is never triggered
});
4

3 回答 3

13

The remove() method doesn't automatically trigger a remove event (because no such event exists), you can do it manually though, with a custom event:

$('#del_span').click(function() {
    $('#to_del').trigger('remove').remove();
});
$('#to_del').on('remove', function() {
    alert("I'm being deleted"); //is never triggered
});

JS Fiddle demo.

Incidentally, in those browsers that support mutation events you could use:

$('#del_span').click(function() {
    $('#to_del').remove();
});
$('body').on('DOMNodeRemoved', '#to_del', function() {
    alert("I, " + this.id + " am being deleted");
});

JS Fiddle demo.

References:

于 2013-08-23T19:03:05.973 回答
4

When you include jQuery UI, the $.cleanData method is overridden to also trigger a remove event. You can mimic this behavior the same way pretty easily:

// copied from jQuery UI Github, link below
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
    for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
        try {
            $( elem ).triggerHandler( "remove" );
        // http://bugs.jquery.com/ticket/8235
        } catch( e ) {}
    }
    _cleanData( elems );
};

https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L16

$.cleanData is called by the.remove method to clean up any data and events stored on the element. Note, this will also result in the remove event being triggered when an element is removed by other means, such as .empty()

于 2013-08-23T19:09:58.573 回答
1

To add to David Thomas answer, I made a a litle plugin to do what you want.

Add this code in your file.

//@Author Karl-André Gagnon
$.hook = function(){
    $.each(arguments, function(){
        var fn = this
        if(!$.fn['hooked'+fn]){
            $.fn['hooked'+fn] = $.fn[fn];
            $.fn[fn] = function(){
                $.fn['hooked'+fn](arguments);
                $(this).trigger(fn, arguments);
            }
        }
    })
}

Then this code :

$.hook('remove')

This is adding a event listener on .remove(). Change nothing to your code and it will work.

A very small example

于 2013-08-23T19:10:25.170 回答