简体   繁体   English

如何使用javascript更改所有链接

[英]How to Change All Links with javascript

I want to change all links of my site. 我想更改我网站的所有链接。 Suppose a link given by .Example http://www.google.com/ changes to http://www.mysite.com/?redirect=http://www.google.com/ 假设.Example http://www.google.com/提供的链接更改为http://www.mysite.com/?redirect=http://www.google.com/

i have my own redirector just i need to change the links via javascript for all url 我有自己的重定向器,我需要通过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
}

You can then make the code run on page-load by wrapping it in a function linked to window.onload event: 然后,您可以通过将代码包装到链接到window.onload事件的函数中来使代码在页面加载上运行:

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

If you use javascript without a framework, you can use the following lines: 如果您在没有框架的情况下使用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')))
});

Just another version with some checks for local links and .forEach() 只是另一个版本,其中包含一些本地链接检查和.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