简体   繁体   English

DOMSubtreeModified事件(和/或替换)仅在<a>标签上?</a>

[英]DOMSubtreeModified Event (and/or replacement) on solely <a> tags?

I've noticied the DOMSubtreeModified event is being deprecated (which is sad news), but I was wondering if there's a way to detect a change in every single tag on a page (I know - this can be really costly, but it has its purpose). 我已经通知DOMSubtreeModified事件已被弃用(这是一个不幸的消息),但是我想知道是否存在一种方法可以检测页面上每个标签的变化(我知道-这确实很昂贵,但是它具有目的)。

Basically, I want to know whenever an <a> tag (node) is created/modified so I can quickly scan its .href and see if it matches a pattern I'm looking for (if it is, I want to redirect it to run my JS (irrelevant to this) instead of navigating to said link). 基本上,我想知道何时创建/修改<a>标记(节点),以便快速扫描其.href并查看其是否与我正在寻找的模式匹配(如果是,我想将其重定向至运行我的JS(与此无关),而不是导航到所述链接)。 I need this to be generic (I don't know IDs/divs/anything except that they're <a href> s, and they have a specific URL pattern I'm looking for. 我需要这个是通用的(我不知道ID / div /任何东西,除了它们是<a href> ,而且它们具有我要查找的特定URL模式。

I know the support for this even is patchy but right now it'd only be used as a Chrome extension (Firefox to come soon after, so I'd have to tinker with it), so it should be okay for now. 我知道对此的支持还很零散,但现在它只能用作Chrome扩展程序(Firefox很快就会推出,所以我必须对其进行修补),所以现在应该还可以。

Let me know if there are extra questions. 让我知道是否还有其他问题。 Thanks! 谢谢!

You can catch the link action when it happens instead. 相反,您可以捕获链接操作。 What is the pattern you are looking for? 您正在寻找什么模式? It's just a matter of "selecting" the right <a> s. 只需“选择”正确的<a> jQuery has attribute selectors for just about any occasion, "starts with", "ends with", "contains", "equals", etc... jQuery在几乎任何情况下都具有属性选择器 ,“以...开头”,“以...结尾”,“包含”,“等于”等。

$('a[href="http://notHere.com"]').on('click',function(event){
    alert("omg don't go there!");
    //window.location="http://www.goHere.com";
    event.preventDefault();
});

jsFiddle jsFiddle

As per comment: 根据评论:

If your page will be changed dynamically you will need to delegate the event binding to something which will definitely always exist, and contain you target. 如果页面将动态更改,则需要将事件绑定委托给肯定会一直存在并包含您目标的对象。

$('body').on('click','a[href="http://notHere.com"]',function(event){
    alert("omg don't go there!");
    //window.location="http://www.goHere.com";
    event.preventDefault();
});

This puts the click handler on the <body> and from there it watches for clicks on the appropriate anchors. 这会将点击处理程序放在<body>然后从那里监视相应锚点的点击。 If you can get closer, go for it, eg: $('#mainContent') 如果可以靠近,那就去吧,例如: $('#mainContent')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM