jQuery watch for domElement changes?

前端 未结 4 2213
囚心锁ツ
囚心锁ツ 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条回答
  • 2020-12-02 19:03

    You can listen for changes to DOM elements (your div for example) by binding onto DOMCharacterDataModified tested in chrome but doesn't work in IE see a demo here
    Clicking the button causes a change in the div which is being watched, which in turn fills out another div to show you its working...


    Having a bit more of a look Shiki's answer to jquery listen to changes within a div and act accordingly looks like it should do what you want:

    $('#idOfDiv').bind('contentchanged', function() {
        // do something after the div content has changed
        alert('woo');
    });
    

    In your function that updates the div:

    $('#idOfDiv').trigger('contentchanged');
    

    See this as a working demo here

    0 讨论(0)
  • 2020-12-02 19:10

    You might want to look into the DOMNodeInserted event for Firefox/Opera/Safari and the onpropertychange event for IE. It probably wouldn't be too hard to utilize these events but it might be a little hack-ish. Here is some javascript event documentation: http://help.dottoro.com/larrqqck.php

    0 讨论(0)
  • 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 '<p>Hello, world</p>'). And that the event will only fire when changed for plain-text strings.

    0 讨论(0)
  • 2020-12-02 19:12

    There is a neat javascript library, mutation-summary by google, that lets you observe dom changes concisely. The great thing about it, is that if you want, you can be informed only of the actions that actually made a difference in the DOM, to understand what I mean you should watch the very informative video on the project's homepage.

    link: http://code.google.com/p/mutation-summary/

    jquery wrapper: https://github.com/joelpurra/jquery-mutation-summary

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