jQuery表达式中的哪些元素$(' a [href * =#]:not([href =#])')定位?

时间:2018-01-30 20:39:22

标签: javascript jquery html

我是jQuery的新手,并且找到了一个代码段,该代码段将滚动到本地或“锚点”所指向的页面的某个部分。链接。

$('a[href*=#]:not([href=#])').click(function() {

        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 500);
          return false;
        }

      }
 });

我知道它必须选择与本地hrefs的链接,但是想知道这两个条款之间的区别是什么。选择器。

4 个答案:

答案 0 :(得分:3)

它匹配包含href #属性的锚点,但不仅 #

答案 1 :(得分:3)

第一个规则将匹配任何带有散列组件的URL,例如<a href="#jump-to-id">

第二个not规则过滤掉任何 空哈希的网址,例如<a href="#">

答案 2 :(得分:3)

a[href*=#]获取包含#的所有链接,但:not([href=#])会排除其#属性中包含href个链接的链接。

将选择此链接:

<a href="http://www.example.com/here#top" title="">Link</a> 

但这不是:

<a href="#" title="">Link</a> 

答案 3 :(得分:1)

jQuery中的属性后面的星号(*)字符表示 attribute contains selector

$('a[href*=#]:not([href=#])')

打破这个局面:

  • a:定位所有 <a> 标记
  • [href*=#]:定位包含 #的所有 href 属性。
  • :not([href=#])目标href属性href 完全 #。< / LI>

因此,简而言之,选择器会定位<a>属性#中包含href的所有#代码,其中href不是 > {{1}}属性的一部分。

考虑到URI使用哈希来表示页面上的ID,这允许jQuery滚动到页面上的元素,而不是简单地“跳转”。它。

希望这有帮助!