无法识别的表达式:a\[href^=#\]

新手上路,请多包涵

我正在尝试制作一个简单的“scrollTo element”函数。

控制台向我显示错误: 语法错误,无法识别的表达式:a[href^=#] for a[href^=#] code

根据对 这个问题 的回复,我将哈希符号用双引号引起来,但现在控制台为此显示 Unexpected token ILLEGAL

请解释我做错了什么以及如何解决它。

这是我的代码:

 $(document).on('click', 'a[href^=#]', function () {
        $('html, body').animate({ scrollTop:  $('section[data-target="'+this.hash.slice(1)+'"]').offset().top }, 1000 );
        return false;
    });
 menu {
  background-color: #1abc9c;
  height: 50px;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  margin: 0;
  padding: 0;
}

menu ul li {
  display: inline-block;
  padding: 0 15px;
}

menu ul li a {
  color: #333;
  text-decoration: none;
}

section {
  height: 300px;
  padding: 60px 0 0 45px;
}

.one {
  background-color: #3498db;
}

.two {
  background-color: #e74c3c;
}

.three {
  background-color: #f39c12;
}

.four {
  background-color: #2c3e50;
}
 <menu>
  <ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
    <li><a href="#four">Four</a></li>
  </ul>
</menu>

<section class="one" data-target="one">Section One</section>
<section class="two" data-target="two">Section Two</section>
<section class="three" data-target="three">Section Three</section>
<section class="four" data-target="four">Section Four</section>

和 JSFiddle 一样

原文由 Alexandr Belov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 289
2 个回答

由于 # 是 jquery 的 元字符,您必须使用 引号 将其包装起来,或者必须使用 \\ 对其进行转义,

 $(document).on('click', 'a[href^="#"]', function () {

要么

$(document).on('click', 'a[href^=\\#]', function () {

演示

原文由 Rajaprabhu Aravindasamy 发布,翻译遵循 CC BY-SA 3.0 许可协议

由我使用 jquery 3.5.1

  • a[href*=#] →返回错误
  • a[href*="#"] →工作正常

原文由 TeoF 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题