如何使用 javascript 更改所有链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13291272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Change All Links with javascript
提问by user1809599
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 更改所有 url 的链接
回答by Beardy
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 */
}
回答by Varon
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);
}
回答by Andreas
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);
}
});
回答by Thomas Kekeisen
$('a').each(function(i, e)
{
var current = $(this);
current.attr('href', 'http://www.mysite.com/?redirect=' + encodeURIComponent(current.attr('href')))
});