【问题标题】:Anchor tag href points to div after clicking it adds undefined in url单击后锚标记href指向div在url中添加未定义
【发布时间】:2021-07-25 16:24:30
【问题描述】:

我有这样的代码:

<a href="#div-part" title="title">go to div part<a>
<form>
...
</form>
<div id="div-part">
<div>

单击锚标记后,滚动会自动移动到 div 部分,但不是在 url 中添加 #div-part,而是在 URL 中添加 #undefined。 例如 localhost:80/index.jsp#undefined.

请帮帮我。

【问题讨论】:

  • 您是否使用了任何可能影响此行为的 js 代码?
  • undefined 不是 HTML 的一部分,因此您显然使用了您未发布的内容。
  • 没有js在里面。纯 HTML,我点击锚点

标签: jquery anchor jquery-events anchor-scroll


【解决方案1】:

这是滚动到特定 div 的解决方案

$(function() {
    $('a').bind('click',function(event){
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1000);       

    });
 });

Check DEMO here.

【讨论】:

  • Jeek,它很好用,但是添加这个 sn-p 不会在 URL 中添加任何内容。但我想在 URL 中添加相应的 div 部分。例如,locahost:80/index.jsp#div-part
  • @user3809019 :好的,我明白了,检查我更新的 jsFiddle 和代码。我删除了这一行:event.preventDefault();
  • jQuery 来解决 OP 所说的纯 html 问题感觉非常糟糕。
猜你喜欢
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多