Nice programing

특정 클래스의 div를 감지하는 jquery가 DOM에 추가되었습니다.

nicepro 2020. 10. 18. 19:34
반응형

특정 클래스의 div를 감지하는 jquery가 DOM에 추가되었습니다.


.on()페이지가로드 된 후 생성되는 div의 이벤트를 바인딩 하는 사용 하고 있습니다. click, mouseenter ... 잘 작동하지만 MyClass 클래스의 새 div가 추가 된시기를 알아야합니다. 나는 이것을 찾고 있어요 :

$('#MyContainer').on({

  wascreated: function () { DoSomething($(this)); }

}, '.MyClass');

어떻게해야합니까? 플러그인없이 전체 앱을 작성해 왔으며 그대로 유지하고 싶습니다.

감사.


이전에는 jQuery의 domManip메소드에 연결하여 모든 jQuery dom 조작을 포착하고 삽입 된 요소 등을 볼 수 있었지만 jQuery 팀은 일반적으로 jQuery 메소드에 연결하는 것이 좋은 솔루션이 아니기 때문에 jQuery 3.0 이상에서이를 종료했습니다. 내부 domManip메서드는 더 이상 핵심 jQuery 코드 외부에서 사용할 수 없도록 만들었습니다 .

Mutation Events는 이전과 같이 사용되지 않습니다.

$(document).on('DOMNodeInserted', function(e) {
    if ( $(e.target).hasClass('MyClass') ) {
       //element with .MyClass was inserted.
    }
});

이것은 피해야하며, 오늘은 Mutation Observers를 대신 사용해야합니다.

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation)
        if (mutation.addedNodes && mutation.addedNodes.length > 0) {
            // element added to DOM
            var hasClass = [].some.call(mutation.addedNodes, function(el) {
                return el.classList.contains('MyClass')
            });
            if (hasClass) {
                // element has class `MyClass`
                console.log('element ".MyClass" added');
            }
        }
    });
});

var config = {
    attributes: true,
    childList: true,
    characterData: true
};

observer.observe(document.body, config);

여기 내 플러그인이 있습니다 -jquery.initialize

사용법은 .each함수를 사용하는 것과 동일 하지만 .initialize요소에 대한 함수를 사용 .each하면 AJAX 등으로 추가하더라도 나중에 추가 코드없이 추가 된 요소도 초기화된다는 점이 다릅니다 .

Initialize는 .each 함수와 정확히 동일한 구문을 갖습니다.

$(".some-element").initialize( function(){
    $(this).css("color", "blue");
});

그러나 이제 .some-element selector와 일치하는 새 요소가 페이지에 나타나면 인스턴스가 초기화됩니다. 새 항목이 추가되는 방식은 중요하지 않으며 콜백 등에 대해 신경 쓸 필요가 없습니다.

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

플러그인은 MutationObserver


이것과 다른 여러 포스트를 검토 한 후, 각각의 최고라고 생각하는 것을 간단하게 추출하여 요소 클래스가 삽입 될 때이를 감지 하고 해당 요소에 대해 조치취했습니다 .

function onElementInserted(containerSelector, elementSelector, callback) {

    var onMutationsObserved = function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length) {
                var elements = $(mutation.addedNodes).find(elementSelector);
                for (var i = 0, len = elements.length; i < len; i++) {
                    callback(elements[i]);
                }
            }
        });
    };

    var target = $(containerSelector)[0];
    var config = { childList: true, subtree: true };
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
    var observer = new MutationObserver(onMutationsObserved);    
    observer.observe(target, config);

}

onElementInserted('body', '.myTargetElement', function(element) {
    console.log(element);
});

저에게 중요한 점은 a) 대상 요소가 "addedNodes"내의 모든 깊이에 존재하고 b) 처음 삽입 될 때만 요소를 처리 할 수있는 기능 (전체 문서 설정을 검색하거나 "이미 처리됨"을 무시할 필요가 없음) 플래그).


3 년 후, "DOM에 추가 된 특정 클래스의 요소"를 듣는 방법입니다 . 다음 html()과 같이 jQuery 함수에 후크를 추가하기 만하면됩니다 .

function Start() {

   var OldHtml = window.jQuery.fn.html;

   window.jQuery.fn.html = function () {

     var EnhancedHtml = OldHtml.apply(this, arguments);

     if (arguments.length && EnhancedHtml.find('.MyClass').length) {

         var TheElementAdded = EnhancedHtml.find('.MyClass'); //there it is
     }

     return EnhancedHtml;
   }
}

$(Start);

This works if you're using jQuery, which I do. And it doesn't rely on the browser-specific event DOMNodeInserted, which is not cross-browser compatible. I also added the same implementation for .prepend()

Overall, this works like a charm for me, and hopefully for you too.


you could use mutation events

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents

EDIT

from MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

Deprecated This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Mutation Observers are the proposed replacement for mutation events in DOM4. They are to be included in Firefox 14 and Chrome 18.

https://developer.mozilla.org/en/docs/Web/API/MutationObserver

MutationObserver provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.

Example usage

The following example was taken from http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/.

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

참고URL : https://stackoverflow.com/questions/10415400/jquery-detecting-div-of-certain-class-has-been-added-to-dom

반응형