繁体   English   中英

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

[英]How to stop html page from jumping when anchor is clicked, but still go to the url in the href?

我知道这个问题似乎与之前的许多问题相似,但主要区别在于我仍然想将 go 转到锚点的href中的 url 并将它们引导到另一个页面。

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

单击锚点时,它会在用户被重定向到href中的 url 之前跳转到页面顶部

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

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

任何帮助,将不胜感激。

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

这篇文章解释了原因。 如果不指定协议,链接将相对于当前请求 URI

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

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

在脚本中:我认为在您的示例中您缺少:window.location。 链接

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM