如何在单击锚点时阻止html页面跳转,但仍转到href中的url?

时间:2019-10-02 17:55:36

标签: javascript

我知道这个问题似乎与之前的很多问题相似,但是主要的区别在于我仍然想转到锚点href中的网址,并将其定向到另一个页面。

这是我的代码: <a class="tile" href="https://www.weather.com">weather<a/>

单击锚点后,它会跳到页面顶部,然后再将用户重定向到href中的网址

我尝试将其添加到JS中以解决它,但无济于事。

this.el.addEventListener('click', (e) => {
    e.preventDefault();
    window.location = this.el.getAttribute('href');
}, false);

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您不需要该javascript,只需尝试将http协议添加到您的url前面。例如: <a class="tile" href="https://www.weather.com" />

This post解释了原因。不指定协议,链接将相对于当前请求URI

答案 1 :(得分:0)

它不应该跳转。但是,在您的情况下,如果它跳了,请使用dud href,然后单击该事件:

<a class="tile" href="javascript:void(0)"  onclick='redirect(event)'>weather<a/>

在脚本中:我想在您的示例中您缺少:window.location。 href

 function redirect(e){
    e.preventDefault();
    window.location.href = "https://www.weather.com"; // notice href
 }
相关问题