[英]Change all external links using jQuery
我想更改博客上的所有外部链接(此处是博客,这就是为什么我要查找jQuery代码)而不更改博客的发布,因为如果这样做,我需要做很多工作。
例如,我的网站是example.com
。 我想将所有外部链接更改为
http://example.com/p/go.html?url=http://externallink.com
无需对我的博客文章进行任何更改。 我没有任何想法开始。
解决: https : //gist.github.com/2342509谢谢大家:DI只需稍作更改即可。
在jQuery中,您可以尝试:
// DOM ready
$(function(){
$('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});
当然,仅当您在HTML中设置了target="_blank"
属性/属性并且希望所有链接都打开相同的网址时,这才起作用。 这个想法源于您希望在其他选项卡/窗口中自动打开外部链接的事实。
如果这不是必需的功能,则可以类似的方式使用自定义data-
属性。 唯一的区别是您将需要循环每个链接,并从中获取数据。
// DOM ready
$(function(){
$('a[data-href]').each(function(){
var anc = $(this),
href = anc.prop('href'),
dataHref = anc.data('href');
anc.prop('href', href + '?url=' + dataHref);
});
});
HTML示例:
<a href="http://example.com/p/go.html" data-href="http://externallink.com">external link</a>
现在,如果您仍然不想要这些信息,则可能需要添加更多信息。
摆脱@Tim Vermaelan的回答,您可以尝试使用此方法,它将检查不以您的网站URL开头的每个链接,而无需依赖于它是target="_blank"
:
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.