簡體   English   中英

如何使用javascript更改所有鏈接

[英]How to Change All Links with javascript

我想更改我網站的所有鏈接。 假設.Example http://www.google.com/提供的鏈接更改為http://www.mysite.com/?redirect=http://www.google.com/

我有自己的重定向器,我需要通過javascript更改所有網址的鏈接

var anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href
}

然后,您可以通過將代碼包裝到鏈接到window.onload事件的函數中來使代碼在頁面加載上運行:

window.onload = function() {
       /* onload code */
}

如果您在沒有框架的情況下使用javascript,則可以使用以下行:

var links, i, le;
links = document.getElementsByTagName('a');
for (i = 0, le = links.length; i < le; i++) {
    links[i].href = "http://www.mysite.com/?redirect=" + encodeURIComponent(links[i].href);
}
$('a').each(function(i, e)
{
    var current = $(this);

    current.attr('href', 'http://www.mysite.com/?redirect=' + encodeURIComponent(current.attr('href')))
});

只是另一個版本,其中包含一些本地鏈接檢查和.forEach()

var links = [].slice.apply(document.getElementsByTagName("a"));
links.forEach(function(link) {
    var href = link.href;

    if (href.length && href.substring(0, 1) !== "#" && href.substring(0, 1) !== "/") {
        link.href = "http://www.mysite.com/?redirect=" + encodeURIComponent(link.href);
        console.log(link.href);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM