Watching for DOM changes, the elegant way

前端 未结 2 1565
我在风中等你
我在风中等你 2020-12-13 09:21

I need to watch for an attribute change on any of the children of a specific DOM element. So far, I have been using mutation events.

The problem was - they were bugg

相关标签:
2条回答
  • 2020-12-13 09:35

    Would this work?

    http://darcyclarke.me/development/detect-attribute-changes-with-jquery/

    $.fn.watch = function(props, callback, timeout){
        if(!timeout)
            timeout = 10;
        return this.each(function(){
            var el      = $(this),
                func    = function(){ __check.call(this, el) },
                data    = { props:  props.split(","),
                            func:   callback,
                            vals:   [] };
            $.each(data.props, function(i) { data.vals[i] = el.css(data.props[i]); });
            el.data(data);
            if (typeof (this.onpropertychange) == "object"){
                el.bind("propertychange", callback);
            } else if ($.browser.mozilla){
                el.bind("DOMAttrModified", callback);
            } else {
                setInterval(func, timeout);
            }
        });
        function __check(el) {
            var data    = el.data(),
                changed = false,
                temp    = "";
            for(var i=0;i < data.props.length; i++) {
                temp = el.css(data.props[i]);
                if(data.vals[i] != temp){
                    data.vals[i] = temp;
                    changed = true;
                    break;
                }
            }
            if(changed && data.func) {
                data.func.call(el, data);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 09:53

    For efficient DOM monitoring with jQuery, you might take a look at the jQuery Behavior Plugin (Disclaimer: I'm the author) which utilizes a optimized version of Live Query. I'm using it in several products for 3 year now, without any problems.

    Edit: Listening for attribute changes would work like this:

    $.behavior({
        'div:first': {
            'changeAttr': function (event, data) {
                console.log('Attribute "' +  data.attribute + '" changed from "' + data.from + '" to "' + data.to + '"');
            }
        }
    });
    
    $('div:first').attr('foo', 'bar');
    
    0 讨论(0)
提交回复
热议问题