简体   繁体   English

JavaScript 在 div 改变时做一些事情

[英]JavaScript do something when div was changed

I have two scripts.我有两个脚本。 One asks my backend about new data in database and if there is something new, add this to div with id 'box'.有人向我的后端询问数据库中的新数据,如果有新数据,请将其添加到 id 为“box”的 div 中。 In second script I want to monitorize this and if something is changed in this div, I want to call my function.在第二个脚本中,我想监视这个,如果这个 div 中的某些内容发生了变化,我想调用我的函数。 How to do that?怎么做?

$(document).ready(function(){
            refreshTable();
        });
        function refreshTable(){ //loading data to div
            $('#messbox').load('getData.php', function(){ setTimeout(refreshTable, 1000); });
        }
        function scroll(){ //function to call
            $("#messbox").scrollTop($("#messbox")[0].scrollHeight);
        }

You can use a MutationObserver to listen for changes in the element's childList :您可以使用MutationObserver来监听元素childList中的变化:

 const targetNode = document.getElementById('target'); const callback = function(mutationsList, observer) { for(const mutation of mutationsList) { if (mutation.type === 'childList') { myFunction() } } }; const observer = new MutationObserver(callback); observer.observe(targetNode, {childList: true}); function myFunction(){ console.log("Change!") }
 <div id="target"></div> <button onclick="target.innerHTML += '<p>Hello World!</p>'">Add something to #target</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM