Javascript jquery选择器没有';t识别到+的链接;锚

Javascript jquery选择器没有';t识别到+的链接;锚,javascript,jquery,ruby-on-rails,Javascript,Jquery,Ruby On Rails,我有一个导航栏,在上面我使用jquery函数,当有人点击特定链接时,它会生成一个平滑的滚动条 我的js代码是: $(document).on('click', 'a[href*=\\#]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 800); }); 当我

我有一个导航栏,在上面我使用jquery函数,当有人点击特定链接时,它会生成一个平滑的滚动条

我的js代码是:

$(document).on('click', 'a[href*=\\#]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 800);
});
当我的导航栏中的元素写成这样时,它工作得很好:

<div class="nav-element">
  <a href="#features">
    <%= t('landing.navbar.features') %>
  </a>
</div> 

但是,当我使用rails帮助程序“link_to”时,它是这样写的:

<div class="nav-element">
  <%= link_to root_path(anchor: "discover") do%>
    <%= t('landing.navbar.discover') %>
  <% end %>
</div>

选择器无法识别我的锚,因为区域设置是在#之前传递的

单击“发现”时,我在控制台中遇到的错误是:

$(document).on('click', 'a[href*=\\#]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 800);
});
未捕获错误:语法错误,无法识别的表达式:/fr#discover

即使我使用
href*=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?我该怎么做才能继续使用我的
链接到
并保持平滑滚动


非常感谢

您需要解析
href
以仅获取哈希值:

// Hook on to all the links containing #
$(document).on('click', 'a[href*="#"]', function (event) {
    event.preventDefault();

    // Get the hash of the href only
    var hash = $(this).attr('href');
    hash = hash.substr(hash.lastIndexOf('#'));

    $('html, body').animate({
        scrollTop: $(hash).offset().top
    }, 800);
});

嗨,梅卡斯,谢谢你的回答。终于成功了!我现在唯一的问题是,当我在另一个页面上时,js代码阻止链接打开。当我点击“discover”时,我在控制台中出现了这个错误
uncaughttypeerror:无法读取未定义的属性'top'“
链接无法打开。我如何调整这个:)?谢谢@ADRAPA问题是,这将阻止任何带有
#
的链接打开。最好的解决方案是确定您希望用于smoothscroll的链接。也许最好的解决方案是在这些链接中添加一个类(可以是
.smoothscroll
),这样您就可以将单击事件仅挂接到这些链接:
$(document).on('click'、'a.smoothscroll'、…)
。我想避免使用此解决方案,但它似乎是唯一有效的解决方案。再次感谢:)@adrappa是的,除了以某种方式识别链接之外,您别无选择-(