jQuery watch for domElement changes?

前端 未结 4 2243
囚心锁ツ
囚心锁ツ 2020-12-02 18:31

I have an ajax callback which injects html markup into a footer div.

What I can\'t figure out is how to create a way to monitor the div for when it\'s contents chang

4条回答
  •  猫巷女王i
    2020-12-02 19:11

    The most effective way I've found is to bind to the DOMSubtreeModified event. It works well with both jQuery's $.html() and via standard JavaScript's innerHTML property.

    $('#content').bind('DOMSubtreeModified', function(e) {
      if (e.target.innerHTML.length > 0) {
        // Content change handler
      }
    });
    

    http://jsfiddle.net/hnCxK/

    When called from jQuery's $.html(), I found the event fires twice: once to clear existing contents and once to set it. A quick .length-check will work in simple implementations.

    It's also important to note that the event will always fire when set to an HTML string (ie '

    Hello, world

    '). And that the event will only fire when changed for plain-text strings.

提交回复
热议问题