jQuery Event : Detect changes to the html/text of a div

后端 未结 13 2278
旧巷少年郎
旧巷少年郎 2020-11-22 06:15

I have a div which has its content changing all the time , be it ajax requests, jquery functions, blur etc etc.

Is there a way

13条回答
  •  北海茫月
    2020-11-22 07:15

    DOMSubtreeModified is not a good solution. It's can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers. MutationObserver will be the answer.

    MDN Doc

    const onChangeElement = (qSelector, cb)=>{
     const targetNode = document.querySelector(qSelector);
     if(targetNode){
        const config = { attributes: true, childList: false, subtree: false };
        const callback = function(mutationsList, observer) {
            cb($(qSelector))
        };
        const observer = new MutationObserver(callback);
        observer.observe(targetNode, config);
     }else {
        console.error("onChangeElement: Invalid Selector")
     }
    }
    

    And you can use it,

    onChangeElement('mydiv', function(jqueryElement){
       alert('changed')
    })
    

提交回复
热议问题