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

Ale*_*lov 5 html jquery jquery-selectors

我试图做一个简单的"scrollTo元素"功能.

控制台显示我的错误: 语法错误,不能识别的表达式:a [^ HREF =#]一个[HREF ^ =#]代码

根据关于这个问题的回复,我将哈希符号包装成双引号,但现在控制台为此显示了意外的标记ILLEGAL.

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

这是我的代码:

$(document).on('click', 'a[href^=#]', function () {
        $('html, body').animate({ scrollTop:  $('section[data-target="'+this.hash.slice(1)+'"]').offset().top }, 1000 ); 
        return false;
    });
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

和JSFiddle中的相同

Raj*_*amy 11

既然#是jquery 的元字符,你必须使用引号来包装它,或者你必须通过使用它来逃避它\\,

$(document).on('click', 'a[href^="#"]', function () {
Run Code Online (Sandbox Code Playgroud)

要么

$(document).on('click', 'a[href^=\\#]', function () {
Run Code Online (Sandbox Code Playgroud)

DEMO