Create a jQuery special event for content changed

后端 未结 4 1054
面向向阳花
面向向阳花 2020-12-07 23:48

I\'m trying to create a jQuery special event that triggers when the content that is bound, changes. My method is checking the content with a setInterval and check if the con

相关标签:
4条回答
  • 2020-12-07 23:57

    also take a look to James similar script (declaring as jquery object method and not as event)

    jQuery.fn.watch = function( id, fn ) {
    
        return this.each(function(){
    
            var self = this;
    
            var oldVal = self[id];
            $(self).data(
                'watch_timer',
                setInterval(function(){
                    if (self[id] !== oldVal) {
                        fn.call(self, id, oldVal, self[id]);
                        oldVal = self[id];
                    }
                }, 100)
            );
    
        });
    
        return self;
    };
    
    jQuery.fn.unwatch = function( id ) {
    
        return this.each(function(){
            clearInterval( $(this).data('watch_timer') );
        });
    
    };
    

    and creating special event

    jQuery.fn.valuechange = function(fn) {
        return this.bind('valuechange', fn);
    };
    
    jQuery.event.special.valuechange = {
    
        setup: function() {
    
            jQuery(this).watch('value', function(){
                jQuery.event.handle.call(this, {type:'valuechange'});
            });
    
        },
    
        teardown: function() {
            jQuery(this).unwatch('value');
        }
    
    };
    

    Anyway, if you need it only as event, you script is nice :)

    0 讨论(0)
  • 2020-12-08 00:01


    I know this post/question is a little old, but these days I was behind a similar solution and I found this:

    $('#selector').bind('DOMNodeInserted', function(e) {
        console.log(e.target);
    });
    

    Source: http://naspinski.net/post/Monitoring-a-DOM-Element-for-Modification-with-jQuery.aspx

    Hope this help someone!

    0 讨论(0)
  • 2020-12-08 00:02

    The finished code in the original question worked for me, thank you! I would just like to note that I am using jquery 1.9.1 and $.event.handle seems to have been removed. I changed the following to get it to work.

    jQuery.event.handle.call(self, {type:'contentchange'});

    to

    jQuery.event.dispatch.call(self, {type:'contentchange'});

    0 讨论(0)
  • 2020-12-08 00:19

    maybe you could try Mutation Observer

    Here are the code:

    mainArea = document.querySelector("#main_area");
    MutationObserver = window.MutationObserver;
    DocumentObserver = new MutationObserver(function() {
           //what you want to run
    });
    
    DocumentObserverConfig = {attributes: true, childList: true, characterData: true, subtree: true};
    
    DocumentObserver.observe(mainArea, DocumentObserverConfig);
    
    0 讨论(0)
提交回复
热议问题