2013-08-23 5 views
3

.remove() 메서드를 사용하여 html 요소를 제거하고 있으며 동시에이 요소에 이벤트 핸들러가 있지만 트리거되지 않았습니다. 왜 그럴 수 있죠? 여기에 jsFiddle 및 코드 : HTMLjquery.remove() 메서드는 .on ('remove') 이벤트를 트리거하지 않습니다.

<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 
}); 
+2

이 없기 때문에? jQuery UI는 하나 추가합니다. http://jsfiddle.net/wHPaz/1/ –

답변

12

자동으로 수동으로하지만 (그런 이벤트가 존재하지 않기 때문에), 당신이 그것을 할 수있는 remove 이벤트를 트리거하지 않습니다 remove() 방법, 맞춤 이벤트 :

$('#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

덧붙여, 돌연변이 이벤트를 지원하는 브라우저에서 다음과 같이 사용할 수 있습니다

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

JS Fiddle demo합니다.

참고 :

+0

'DOMNodeRemoved'의 사용은 더 이상 사용되지 않으며 성능 문제로 인해 권장하지 않습니다. https://developer.mozilla.org/en-US/docs/Web/Guide/ 이벤트/Mutation_events – oriadam

4

jQuery UI를 포함하면 $.cleanData 메서드가 재정의되어 remove 이벤트가 트리거됩니다. 당신은 아주 쉽게이 동작을 같은 방법으로 모방 할 수

// 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은 요소에 저장된 데이터 및 이벤트를 정리합니다 .remove 방법에 의해 호출됩니다. 요소가 다른 수단 (예 : .empty()

1

)에 추가 될 때 제거 이벤트가 트리거됨에 유의하십시오. David Thomas answer에 추가하려면 원하는 리플리 플러그인을 작성하십시오.

파일에이 코드를 추가하십시오.

//@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); 
      } 
     } 
    }) 
} 

그런 다음이 코드 :

$.hook('remove') 

이것은 .remove()에 이벤트 리스너를 추가하고있다. 코드에 아무 것도 변경하지 않아도됩니다. 더 제거 이벤트는

A very small example

관련 문제