Detect element content changes with jQuery

后端 未结 15 2255
余生分开走
余生分开走 2020-11-22 04:19

change() function works and detects changes on form elements, but is there a way of detecting when a DOM element\'s content was changed?

This does not w

15条回答
  •  长情又很酷
    2020-11-22 05:23

    I wrote a snippet that will check for the change of an element on an event.

    So if you are using third party javascript code or something and you need to know when something appears or changes when you have clicked then you can.

    For the below snippet, lets say you need to know when a table content changes after you clicked a button.

    $('.button').live('click', function() {
    
                var tableHtml = $('#table > tbody').html();
                var timeout = window.setInterval(function(){
    
                    if (tableHtml != $('#table > tbody').
                        console.log('no change');
                    } else {
                        console.log('table changed!');
                        clearInterval(timeout);
                    }
    
                }, 10);
            });
    

    Pseudo Code:

    • Once you click a button
    • the html of the element you are expecting to change is captured
    • we then continually check the html of the element
    • when we find the html to be different we stop the checking

提交回复
热议问题