How can I Observe the contents of an 'a' t

2020-06-02 16:41发布

问题:

I have a blank <a> tag that content is loaded into via an external piece of javascript. I want to observe the <a> and when its content changes perform another task. The content will only ever change once.

Can this be done?

I am using also using jQuery.

Thanks in advance

回答1:

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.



回答2:

You can try monitoring the .html() of the tag to see if it changes to anything else...

Maybe have a timed function (executing every n-seconds) that monitors the content (.html()) of the element until it changes and then stops monitoring it. Maybe something in the vein of:

var monitor = true;
var doMonitor = function() {
  monitor = $("#theanchor").html() != "the initial value";
  if (monitor)
    setTimeout(doMonitor,500);
};
setTimeout(doMonitor,500);

In theory this should work, but I haven't tested it.



回答3:

You could make use of the DOMSubtreeModified event. That event fires at an element when it's contents change.

$('a').bind('DOMSubtreeModified', function() {
    // contents changed   
});

Note: this event does not fire in Opera and older versions of IE (it works in IE9 though).

Live demo: http://jsfiddle.net/simevidas/pLvgM/



回答4:

What do you mean content of an a tag? You can do this like so:

$('#linkElementID').html();

or get an attribute like so:

$('#linkElementID').attr("title"); //Title Attribute 
$('#linkElementID').attr("href"); //href Attribute etc etc 

I don't think there is an event that is fired when a tag changes, the .change() event is only fired by input areas and select lists.

You would need to check after the event that loads the newly inserted content.