【问题标题】:How to stop html page from jumping when anchor is clicked, but still go to the url in the href?单击锚点时如何阻止html页面跳转,但仍然转到href中的url?
【发布时间】:2019-10-02 17:55:36
【问题描述】:

我知道这个问题似乎与之前的许多问题相似,但主要区别在于我仍然想转到锚点 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);

任何帮助将不胜感激。

【问题讨论】:

  • 你需要<a class="tile" href="https://www.weather.com" />(你将浏览器发送到http://yoursite.com/www.weather.com之类的东西)
  • @ChrisG 以后,有时最好不要去掉 JavaScript 问题上的 jQuery 标签,即使问题没有明确提及;这是 OP 表示他们愿意接受使用 jQuery 的答案的另一种方式。
  • @TylerRoper 真;在提交编辑之前,我曾短暂考虑过重新添加它,但最终没有。这似乎与这个问题并不特别相关。
  • href=https://www.weather.com 您是否缺少https://www.weather.com 周围的" "?应该是href="https://www.weather.com"。除此之外,我无法在任何地方重新创建它;单击<a> 到外部站点不会在页面上跳转;它只是按预期导航。
  • 拥有自闭合锚标记是无效的,一方面。锚文本在哪里?这不是正常行为,这让我认为信息中缺少某些内容。该标签在页面中的位置的上下文会很有用。

标签: javascript


【解决方案1】:

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

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

【讨论】:

  • 谢谢!但是,我有一个错字。我确实在href 中有协议。
【解决方案2】:

它不应该跳转。但是,在您的情况下,如果它跳转然后使用 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
 }

【讨论】:

  • 我可以在我提供的代码中找到我的链接,但它仍然会跳转。我认为这个问题与焦点有关。
  • @tim 我刚刚编辑了我的帖子。缺少主要部分我认为我的锚标记代码没有反映在帖子中。刚刚编辑。试试看
猜你喜欢
  • 2014-07-07
  • 2015-07-12
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2011-04-09
相关资源
最近更新 更多