How can I Observe the contents of an 'a' tag - jquery

后端 未结 4 950
轮回少年
轮回少年 2021-02-07 18:05
4条回答
  •  死守一世寂寞
    2021-02-07 18:39

    You can use a mixture out of jQuery && DOM Level 3 events (see browser support below).

    If you want to check for any changes within the content, you could do this:

    var $a = $('a');
    
    $a.one('DOMNodeInserted', function(e) {
        console.log('content changed!: ', e);    
    
        console.log('new content: ', $(this).html());   
    });
    
    $a.one('DOMAttrModified', function(e) {
        console.log('attribute changed!: ');        
    
        console.log('attribute that was changed: ', e.attrName);
    });
    

    See this code in action: http://jsfiddle.net/wJbMj/1/

    Reference: DOMNodeInserted, DOMAttrModified


    While the above solution is actually pretty convinient to me, it'll only work in browser that support those events. To have a more generic solution, you can hook into jQuerys setter methods. The downside in this solution is, that you will only catch changes that were done through jQuery.

    var _oldAttr = $.fn.attr;
    $.fn.attr = function() {
        console.log('changed attr: ', arguments[0]);
        console.log('new value: ', arguments[1]);
        return _oldAttr.apply(this, arguments);
    };
    

    You could hook into .text() and .html() the exact same way. You would need to check if the this value within the overwritten methods represent the correct DOMnode.

提交回复
热议问题