a [href ^ =“#”]和a [href * = \\#]

时间:2020-05-04 14:09:07

标签: javascript dom css-selectors

有什么区别
'a[href^="#"]'

'a[href*=\\#]'

我想创建一个平滑滚动的JavaScript,以影响网站上的所有内部链接。

这是完整的脚本。

 jQuery(document).ready(function($) {
      $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();
    var target = this.hash,
        $target = $(target);

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );

1 个答案:

答案 0 :(得分:0)

  • ^=是“属性以”开头的CSS选择器
  • *=是“属性包含” CSS选择器

您需要\\才能在两种情况下转义:

  • a[href*=#]不是有效的CSS选择器;必须为a[href*=\#]a[href*="#"]
  • \需要使用JavaScript字符串文字本身进行转义

let a = 'a[href^="#"]';
let b = 'a[href*=\\#]';
let c = 'a[href*="#"]';
let d = 'a[href*=#]';
console.log(a, document.querySelectorAll(a).length);
console.log(b, document.querySelectorAll(b).length);
console.log(c, document.querySelectorAll(c).length);
try {
  document.querySelectorAll(d);
} catch(err) {
  console.log(err.message);
}
<a href="#foo">Blah</a>
<a href="foo#bar">Blah</a>

相关问题