【问题标题】:Unrecognized expression: a[href^=#]无法识别的表达式:a[href^=#]
【发布时间】:2016-07-20 09:26:02
【问题描述】:

我正在尝试制作一个微不足道的“scrollTo 元素”功能。

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

根据this question 上的回复,我将井号用双引号括起来,但现在控制台为此显示 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>

and the same in JSFiddle

【问题讨论】:

  • 你到底是怎么包装的?包装它对我来说很好。

标签: jquery html jquery-selectors


【解决方案1】:

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

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

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

DEMO

【讨论】:

  • 看来我第一次用不正确的引号将它包裹起来。现在可以了!
  • 不仅是 jQuery 中的元字符,在通用 JS 中也是如此 .querySelectorAll() ! :) 并且同样的修复在那里也有效:)
【解决方案2】:

尝试改成

a[href*=\\#]

这对我有用:)

【讨论】:

    【解决方案3】:

    由我使用 jquery 3.5.1

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

    【讨论】:

    • 感谢您的回答,但这不是线程所有者所要求的。虽然^ 表示属性必须以特定字符串“开始”,但* 不限于字符串的开头。
    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多