jQuery on remove not working parent node fire empty()

时间:2015-03-25 12:33:39

标签: jquery

我使用jQuery ajax。根据我删除或添加的答案。但是jQuery.on功能不起作用。

示例:

<div id="selector">
    <span>Hello World</span>
</div>

$(document).ready(function(){
    $(document).on('remove','span',function(){
        alert(" first object object deleted");
    });

    setTimeout(function(){
        $('#selector').empty();
    },3000);
});

jsFiddle.net https://jsfiddle.net/1zuau1f6/5/

编辑:我的问题不明白。问题我正在纠正..

--- ---更新

我在jquery.ui框架中找到解决方案

$.cleanData = ( function( orig ) {
    return function( elems ) {
        var events, elem, i;
        for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
            try {

                // Only trigger remove when necessary to save time
                events = $._data( elem, "events" );
                if ( events && events.remove ) {
                    $( elem ).triggerHandler( "remove" );
                }

                // Http://bugs.jquery.com/ticket/8235
            } catch ( e ) {}
        }
        orig( elems );
    };
} )( $.cleanData );

4 个答案:

答案 0 :(得分:1)

尝试这样的尝试..

setTimeout(function(){
    $('#selector').trigger('remove').remove();       
},3000);

fiddle Demo

答案 1 :(得分:0)

两个问题:

1)您必须包含jquery UI库才能使用remove事件。

2)事件委托不适用于remove。因此使用:

$('div').on('remove',function(){
    alert(" first object object deleted");
});

<强> Working Demo

答案 2 :(得分:0)

$(document).ready(function(){

  $(document).on('remove','div',function(){
    alert("Element was removed");
   });     
  setTimeout(function(){
    $('#selector').trigger('remove');
   },3000);
}); 

Demo

希望这有帮助

答案 3 :(得分:0)

你也可以覆盖jQuery.remove()函数:

$(function(){
    var origRemove = $.fn.remove;

    $.fn.remove = function newRemove() {
        var jQ = this.trigger("remove");
        return origRemove.apply(jQ, arguments);
    };    

    $(document).on('remove','div',function(){
        alert("object gonna be deleted");
    });

    setTimeout(function(){
        $('#selector').remove();        
    },3000);
})