sourcecode

돔 요소에서 추가/제거되는 요소를 탐지하는 방법은 무엇입니까?

copyscript 2023. 10. 16. 21:59
반응형

돔 요소에서 추가/제거되는 요소를 탐지하는 방법은 무엇입니까?

내가 있었다고 치자.div#parent그리고 나는.append그리고.removejquery를 이용한 요소들.그런 이벤트가 발생했을 때 어떻게 감지할 수 있습니까?div#parent요소?

DOMNodeInserted 및 DOMNodeRemoved와 같은 돌연변이 이벤트를 사용하지 마십시오.

대신 IE10 이하(사용 가능)를 제외한 모든 최신 브라우저에서 지원되는 DOM Mutation Observer를 사용합니다.돌연변이 관측기는 설계상의 결함으로 인해 성능이 낮은 것으로 밝혀졌기 때문에 (사용이 중단된) 돌연변이 사건을 대체하기 위한 것입니다.

var x = new MutationObserver(function (e) {
  if (e[0].removedNodes) console.log(1);
});

x.observe(document.getElementById('parent'), { childList: true });

@Quantas가 자신의 답변에서 제시한 돌연변이 관찰자 사용


다음 메서드는 더 이상 사용되지 않습니다.

DOMNodeInsertedDOMNodeRemoved를 사용할 수 있습니다.

$("#parent").on('DOMNodeInserted', function(e) {
    console.log(e.target, ' was inserted');
});

$("#parent").on('DOMNodeRemoved', function(e) {
    console.log(e.target, ' was removed');
});

MDN 문서

당신은 결박해야 합니다.DOMSubtreeModified이벤트성

$("#parent").bind("DOMSubtreeModified",function(){
  console.log('changed');
});

http://jsfiddle.net/WQeM3/

이는 제가 아래의 가장 중요한 답을 언급하는 것이 아니라, @DenisKolodin의 질문에 답하기 위해, 당신은 다음과 같은 것을 할 수 있습니다.

function watchElForDeletion(elToWatch, callback, parent = document.querySelector('body')){
  const observer = new MutationObserver(function (mutations) {

    // loop through all mutations
    mutations.forEach(function (mutation) {

        // check for changes to the child list
        if (mutation.type === 'childList') {

            // check if anything was removed and if the specific element we were looking for was removed
            if (mutation.removedNodes.length > 0 && mutation.removedNodes[0] === elToWatch) {
                callback();
            }
        }
    });
  });

  // start observing the parent - defaults to document body
  observer.observe(parent, { childList: true });
};

기본적으로 상위 요소가 본문 요소로 설정되어 있으며, 원하는 특정 요소가 삭제된 경우에만 콜백을 실행합니다.

우리는 socket.io 을 사용하는 것 같습니다.

왜냐하면 우리는 어떤 요소가 추가되어야 하는지를 감지하고 그 다음에 어떤 요소가 제거될지 추측할 수 있기 때문입니다.

어쩌면 가능할지도 모릅니다.

감사해요.

언급URL : https://stackoverflow.com/questions/20156453/how-to-detect-element-being-added-removed-from-dom-element

반응형