Detect element content changes with jQuery

后端 未结 15 2246
余生分开走
余生分开走 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:07

    what about http://jsbin.com/esepal/2

    $(document).bind("DOMSubtreeModified",function(){
      console.log($('body').width() + ' x '+$('body').height());
    })
    

    This event has been deprecated in favor of the Mutation Observer API

    0 讨论(0)
  • 2020-11-22 05:07

    Try to bind to the DOMSubtreeModified event seeign as test is also just part of the DOM.

    see this post here on SO:

    how-do-i-monitor-the-dom-for-changes

    0 讨论(0)
  • 2020-11-22 05:09

    You can add a callback option to html (,or any) function:

    $.fn.oldHtml = $.fn.html;
    $.fn.html = function(html,fn){
      fn = fn || function(){};
      var result =  this.oldHtml(html);
      fn();
      return result;
    };
    $('body').html(11,function(){alert("haha");});
    

    Demo here.

    You do the change on some element, not the element is forced to change by something that you have to catch.

    0 讨论(0)
  • 2020-11-22 05:14

    And with HTML5 we have native DOM Mutation Observers.

    0 讨论(0)
  • 2020-11-22 05:18

    We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

    For Example :

    $("body").on('DOMSubtreeModified', "#content", function() {
        alert('Content Modified'); // do something
    });
    
    0 讨论(0)
  • 2020-11-22 05:21

    The browser will not fire the onchange event for <div> elements.

    I think the reasoning behind this is that these elements won't change unless modified by javascript. If you are already having to modify the element yourself (rather than the user doing it), then you can just call the appropriate accompanying code at the same time that you modify the element, like so:

     $("#content").html('something').each(function() { });
    

    You could also manually fire an event like this:

     $("#content").html('something').change();
    

    If neither of these solutions work for your situation, could you please give more information on what you are specifically trying to accomplish?

    0 讨论(0)
提交回复
热议问题