Javascript更改链接目标

时间:2015-12-21 14:11:53

标签: javascript

我正在尝试创建一个javascript,使<a>转到另一个链接,而不是其href中指定的链接。例如。我想要

<a href="http://www.example.com/some-page">

转而去:

http://www.newexamplesite.com/http:%252F%252Fwww.example.com%252Fsome-page

不幸的是,我无法访问此应用程序的jQuery。必须是纯粹的javascript。

我正在寻找可以包含在实际<a>标记中的一些JavaScript:

<a onclick="" href="http://www.example.com/some-page">
  

请注意,必须检测原始链接,并且需要所有/   要替换为%252F

4 个答案:

答案 0 :(得分:2)

试试这个:

<a onclick="window.location.href = 'http://newlink.com/' + encodeURIComponent(this.href); return false;" href="http://www.example.com/some-page/">Go to new link</a>

答案 1 :(得分:0)

您应该阻止默认事件(即转到href指定的链接)并转到另一个链接。

<a onclick="event.preventDefault();location.href='http://www.newexamplesite.com/'+this.href.replace(/\//g,'%252F')"
   href="http://www.example.com/some-page">
   test
</a>

答案 2 :(得分:0)

尝试以下方法:

<a onclick="event.preventDefault();location.href='http://www.uol.com.br/'" href="http://www.example.com/some-page">Link Text</a>

event.preventDefault应停止锚元素的默认行为(即 - 将用户引导至a href内的网站。

编辑:忘记了函数调用中的括号!

答案 3 :(得分:-1)

您可以使用如下函数调用替换href URL:

<a href="javascript:goToLink()" />
<script>
 function goToLink(){
  // your link selection logic goes here
      .....

// when you have selected the link you want to go to assign it to the window location.href attribute and the browser will redirect the user to the specified link
window.location.href = "..selected link...";
}
</script>