我的几个页面中有以下 URL(http://something.com)..
<a href="http://something.com">Home</a>
<a href="index.html">Index</a>
<a href="about.html">About</a>
<a href="contact.php">Contact</a>
<a href="#">Same</a>
<a hre="http://example.com/home.html">New Home</a>
<a href="../services.html">Services</a>
我想要的是将所有链接转换为...
<a href="http://this.com/?url=http://something.com">Home</a>
<a href="http://this.com/?url=http://something.com/index.html">Index</a>
<a href="http://this.com/?url=http://something.com/about.html">About</a>
<a href="http://this.com/?url=http://something.com/contact.php">Contact</a>
<a href="#">Same</a>
<a hre="http://this.com/?url=http://example.com/home.html">New Home</a>
<a href="../services.html">Services</a>
所以基本上我不想转换 "#"
或 "../"
这样的链接。
我是 JS 菜鸟。
通过我的努力,在 w3schools 的帮助下......我试图完成的事情:-
<script type="text/javascript">
var url= document.getElementByTagName(a);
var pattern = /..\//g;
var result = pattern.test(url);
if(url.href != "#" || result === "false" ) {
var nurl = url.replace("http://this.com/?url="+url.href, url.href);
}
</script>
而且我什么也做不了...请帮忙,我该如何修改 URL 并添加 http://this.com/?url=My_web_page_url_here
。
更新 我用
替换了我的 javascript<script type="text/javascript">
var links = document.links;
var i = links.length;
while (i--) {
if (links[i].href.slice(-1) == "#" ||
links[i].getAttribute("href").slice(0, 3) == "../") {
continue;
}
links[i].href = "http://this.com/?url=" + encodeURIComponent(links[i].href);
}
</script>
并且所有 url 仍然以相同的方式没有附加。
最佳答案
试试这个...
var links = document.links;
var i = links.length;
while (i--) {
if (links[i].href.slice(-1) == "#" ||
links[i].getAttribute("href").slice(0, 3) == "../") {
continue;
}
links[i].href = "http://this.com/?url=" + encodeURIComponent(links[i].href);
}
jsFiddle .
我对参数进行了编码,但如果您不想对其进行编码,就像在您的示例中一样,请停止对 encodeURIComponent()
的调用。
关于javascript - 如何通过 javascript 将所有 href 链接附加到重定向器 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549997/