[英]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.