如果链接不以特定网址/域开头,Jquery 将链接更改为 _blank
我知道 $("a[href='http://testtesttest.org/']").attr("target", "_blank");
将查找并更改所有匹配的链接测试网址,但我想知道如何仅更改与该网址不匹配的链接。本质上是将用户带到其他网站的链接——外部链接
I know that $("a[href='http://testtesttest.org/']").attr("target", "_blank");
will find and change all links that match the test url, but I'd like to know how to only change the links that do NOT match that URL. Essentially links that would take users to other webites -- outside links
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
:not
:如果您想选择所有这些不以该 URL 开头,则必须使用 属性以选择器
^=
开头:您提到:
这取决于内部 URL 结构的一致性。例如,前面显示的选择器还将选择诸如
或 之类
的链接,这些链接显然是内部的。如果每个内部链接都以您的域名开头,那就没问题了。如果没有,您可以调整这些链接,以获得一致的结构,或者使用另一个选择器:
这将确保不选择具有绝对和相对 URL 的链接。
如果您还具有与其他协议的链接,例如
file:
,那么它会变得更加复杂。You can use
:not
:If you want to select all those that don't start with this URL, you have to use the attribute starts with selector
^=
:You mention:
That depends on how consistent the structure of internal URLs is. E.g. the previous shown selector would also select links such as
or
which are clearly internal. If every internal link starts with your domain name, than it is fine. If not, you either have the possibility to adjust those links, to have a consistent structure, or to use another selector:
This will make sure that links with absolute and relative URLs are not selected.
If you also have links with other protocols, such as
file:
, it becomes even more involved.来自 jQuery 选择器的文档:
http://api.jquery.com/not-selector/
From the documentation on jQuery selectors:
http://api.jquery.com/not-selector/
试试这个:
这将为您提供所有不以您的域开头的网址。
Try this:
This will give you all URLs that don't start with your domain.