How to Change All Links with javascript

眉间皱痕 提交于 2021-02-05 20:31:11

问题


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/

i have my own redirector just i need to change the links via javascript for all url


回答1:


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 = function() {
       /* onload code */
}



回答2:


If you use javascript without a framework, you can use the following lines:

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);
}



回答3:


$('a').each(function(i, e)
{
    var current = $(this);

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



回答4:


Just another version with some checks for local links and .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);
    }
});


来源:https://stackoverflow.com/questions/13291272/how-to-change-all-links-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!