jQuery-요소가 DOM에서 제거 될 때 이벤트 트리거
요소가 페이지에서 제거 될 때 일부 js 코드를 실행하는 방법을 찾으려고합니다.
jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */
다음과 같은 이벤트가 있습니까?
jQuery('#some-element').onremoval( function() {
// do post-mortem stuff here
});
감사.
방금 확인하면 현재 버전의 JQuery에 이미 내장되어 있습니다.
jQuery-v1.9.1
jQuery UI-v1.10.2
$("#myDiv").on("remove", function () {
alert("Element was removed");
})
중요 : 이것은 JQuery UI 스크립트 (JQuery 아님)의 기능이므로 두 스크립트 (jquery 및 jquery-ui)를 모두로드해야 작동합니다. 예를 들면 다음과 같습니다. http://jsfiddle.net/72RTz/
이를 위해 jQuery 특수 이벤트 를 사용할 수 있습니다 .
간단하게 말하면
설정:
(function($){
$.event.special.destroyed = {
remove: function(o) {
if (o.handler) {
o.handler()
}
}
}
})(jQuery)
용법:
$('.thing').bind('destroyed', function() {
// do stuff
})
Pierre와 DesignerGuy의 의견에 대한 부록 :
호출시 콜백이 발생하지 않도록하려면 $('.thing').off('destroyed')
if 조건을 다음과 같이 변경하십시오.if (o.handler && o.type !== 'destroyed') { ... }
DOMNodeRemoved 이벤트 (DOM 레벨 3 WC3 스펙의 일부)에 바인딩 할 수 있습니다.
Firefox 및 Chrome의 최신 릴리스 인 IE9에서 작동합니다.
예:
$(document).bind("DOMNodeRemoved", function(e)
{
alert("Removed: " + e.target.nodeName);
});
바인딩 할 때 요소를 삽입 할 때 알림을받을 수도 있습니다. DOMNodeInserted
요소를 제거하는 기본 제공 이벤트는 없지만 가짜 확장 jQuery의 기본 remove 메소드를 사용하여 작성할 수 있습니다. 참조를 유지하려면 실제로 제거하기 전에 콜백을 호출해야합니다.
(function() {
var ev = new $.Event('remove'),
orig = $.fn.remove;
$.fn.remove = function() {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
})();
$('#some-element').bind('remove', function() {
console.log('removed!');
// do pre-mortem stuff here
// 'this' is still a reference to the element, before removing it
});
// some other js code here [...]
$('#some-element').remove();
참고 :이 답변의 일부 문제는 다른 포스터에 의해 설명되었습니다.
- 노드를
html()
replace()
다른 jQuery 메소드 를 통해 제거하면 작동하지 않습니다. - 이 이벤트는 거품
- jQuery UI도 remove를 재정의합니다.
이 문제에 대한 가장 우아한 해결책은 다음과 같습니다. https://stackoverflow.com/a/10172676/216941
후킹 .remove()
페이지에서 요소를 제거하는 방법에는 여러 가지가 (예를 들어, 사용하여 있기 때문에이 문제를 처리하는 가장 좋은 방법이 아니다 .html()
, .replace()
등).
내부적으로 다양한 메모리 누수 위험을 방지하기 위해 내부적으로 jQuery는 jQuery.cleanData()
제거하는 데 사용 된 메소드에 관계없이 제거 된 각 요소에 대해 함수를 호출하려고 시도 합니다.
자세한 내용은이 답변을 참조하십시오 : javascript memory leaks
따라서 최상의 결과를 얻으 cleanData
려면 jquery.event.destroyed 플러그인이 수행 하는 기능과 정확히 일치 하는 함수를 연결해야합니다 .
http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js
jQuery UI를 사용하는 사람들 :
jQuery를 UI가 구현하는 jQuery를 방법의 일부를 무시하고있다 remove
명시 적으로 지정된 요소를 제거 할뿐만 아니라, 경우 요소가있는 자동 세척의 jQuery 방법으로 DOM에서 (예를 들어, 제거 도착하지 않을 경우에만 처리됩니다 이벤트 replace
, html
등) . 이것은 기본적으로 jQuery가 DOM 요소와 관련된 이벤트와 데이터를 "정리"할 때 발생하는 동일한 이벤트에 후크를 넣을 수있게합니다.
John Resig는 향후 jQuery 코어 버전에서이 이벤트를 구현하려는 아이디어에 대해 공개하고 있지만 현재 어디에 있는지 잘 모르겠습니다.
바인딩을 사용 하여이 답변 을 얻을 수 없었습니다 (업데이트 는 여기 참조 ). 그러나 그 주위에 방법을 찾을 수있었습니다. 답은 '파기'이벤트를 트리거 한 'destroy_proxy'특수 이벤트를 작성하는 것이 었습니다. 이벤트 리스너를 'destroyed_proxy'와 'destroyed'모두에 배치 한 후 바인드를 해제하려면 '파기 된'이벤트를 바인드 해제하십시오.
var count = 1;
(function ($) {
$.event.special.destroyed_proxy = {
remove: function (o) {
$(this).trigger('destroyed');
}
}
})(jQuery)
$('.remove').on('click', function () {
$(this).parent().remove();
});
$('li').on('destroyed_proxy destroyed', function () {
console.log('Element removed');
if (count > 2) {
$('li').off('destroyed');
console.log('unbinded');
}
count++;
});
여기는 바이올린입니다
jQuery UI를 사용하지 않는 솔루션
( jQuery UI 프레임 워크에서이 확장을 추출했습니다 )
함께 작동 : empty()
및 html()
및remove()
$.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 );
이 솔루션을 사용 하면 이벤트 핸들러를 바인드 해제 할 수도 있습니다 .
$("YourElemSelector").off("remove");
시도 해봐! - 예
$.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);
$("#DivToBeRemoved").on("remove", function() {
console.log("div was removed event fired");
});
$("p").on("remove", function() {
console.log("p was removed event fired");
});
$("span").on("remove", function() {
console.log("span was removed event fired");
});
// $("span").off("remove");
$("#DivToBeRemoved").on("click", function() {
console.log("Div was clicked");
});
function RemoveDiv() {
// $("#DivToBeRemoved").parent().html("");
$("#DivToBeRemoved").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>
<div class="container">
<br>
<button onclick="RemoveDiv();">Click here to remove div below</button>
<div id="DivToBeRemoved">
DIV TO BE REMOVED
contains 1 p element
which in turn contains a span element
<p>i am p (within div)
<br><br><span>i am span (within div)</span></p>
</div>
</div>
추가 데모-jsBin
I like mtkopone's answer using jQuery special events, but note that it doesn't work a) when elements are detached instead of removed or b) when some old non-jquery libraries use innerHTML to destroy your elements
I'm not sure there is an event handle for this, so you would have to keep a copy of the DOM and compare to the existing DOM in some kind of polling loop - which could be quite nasty. Firebug does this though - if you inspect the HTML and run some DOM-changes, it highlights the changes in yellow in the Firebug console for a short time.
Alternatively, you could create a remove function...
var removeElements = function(selector) {
var elems = jQuery(selector);
// Your code to notify the removal of the element here...
alert(elems.length + " elements removed");
jQuery(selector).remove();
};
// Sample usage
removeElements("#some-element");
removeElements("p");
removeElements(".myclass");
This is how to create a jQuery live remove listener:
$(document).on('DOMNodeRemoved', function(e)
{
var $element = $(e.target).find('.element');
if ($element.length)
{
// do anything with $element
}
});
Or:
$(document).on('DOMNodeRemoved', function(e)
{
$(e.target).find('.element').each(function()
{
// do anything with $(this)
}
});
The "remove" event from jQuery works fine, without addition. It might be more reliable in time to use a simple trick, instead of patching jQuery.
Just modify or add an attribute in the element you are about to remove from the DOM. Thus, you can trigger any update function, that will just ignore elements on way to be destroyed, with the attribute "do_not_count_it".
Suppose we have a table with cells corresponding to prices, and that you need to show only the last price: This is the selector to trigger when a price cell is deleted (we have a button in each line of the table doing that, not shown here)
$('td[validity="count_it"]').on("remove", function () {
$(this).attr("validity","do_not_count_it");
update_prices();
});
And here is a function that finds the last price in the table, not taking account of the last one, if it was the one that was removed. Indeed, when the "remove" event is triggered, and when this function is called, the element is not removed yet.
function update_prices(){
var mytable=$("#pricestable");
var lastpricecell = mytable.find('td[validity="count_it"]').last();
}
In the end, the update_prices() function works fine, and after that, the DOM element is removed.
referencing to @David answer:
When You want to do soo with another function, eg. html() like in my case, don't forget to add return in new function:
(function() {
var ev = new $.Event('html'),
orig = $.fn.html;
$.fn.html = function() {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
})();
This.
$.each(
$('#some-element'),
function(i, item){
item.addEventListener('DOMNodeRemovedFromDocument',
function(e){ console.log('I has been removed'); console.log(e);
})
})
'Programing' 카테고리의 다른 글
원래 파일로 로컬 파일을 강제로 덮어 씁니까? (0) | 2020.05.07 |
---|---|
JavaScript에서 외부 로컬 JSON 파일을 읽는 방법은 무엇입니까? (0) | 2020.05.07 |
Dapper ORM을 사용하여 ID를 입력 할 때 *에서 * 선택 (…) (0) | 2020.05.07 |
YAML에서 인디케이터 문자 (예 : 또는-)를 이스케이프 처리하는 방법 (0) | 2020.05.07 |
R이 지수 표기법 (예 : e + 10)을 사용하지 않도록 강제합니까? (0) | 2020.05.06 |