我如何观察'a'标签的内容 - jquery [英] How can I Observe the contents of an 'a' tag - jquery

查看:83
本文介绍了我如何观察'a'标签的内容 - jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空白的< a> 标签,该内容通过外部JavaScript加载。我想观察< a> ,当其内容更改执行另一个任务时。这个内容只会改变一次。

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.

可以这样吗?

我也在使用jQuery。

I am using also using jQuery.

提前感谢

推荐答案

您可以使用混合物 jQuery && DOM 3级事件(请参阅下面的浏览器支持)。

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);
});

请参阅此代码: http://jsfiddle.net/wJbMj/1/

参考:< a href =http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted =nofollow> DOMNodeInserted , DOMAttrModified

虽然上述解决方案实际上非常方便我,但它只适用于支持这些事件的浏览器。要拥有一个更通用的解决方案,您可以将钩住到jQuerys setter方法。这个解决方案的缺点是,你只会捕获通过jQuery完成的更改。

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);
};

您可以钩入 .text() .html()完全相同的方式。您需要检查覆盖方法中的值是否代表正确的DOMnode。

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.

这篇关于我如何观察'a'标签的内容 - jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆