jQuery - 获取多个元素的属性并将其与其他元素的id匹配?

jQuery - Get the attribute of multiple elements and match it to other elements' ids?

如何让 jQuery 将 id 与属性进行比较,如果匹配,则向具有匹配属性的元素添加 .activeclass?

我正在尝试重构冗长且重复的 jQuery 代码。我已将 waypoints 设置为在滚动时触发,一旦您到达某个部分,它会在引用该部分的菜单 link 中添加一个活动 class。这是我能做到的最好的,但它不起作用。

$('section').waypoint(function(direction) {
  if (direction === 'down') {
    $('nav a').removeClass('active-nav');
    var linkName = $('nav a').map( function() {
    return $(this).attr('href');
    }).get();
    if(linkName == $('section[id]')){
         $(this).addClass('active-nav');
        }
  }
}, {
  offset: '25%'
});

这背后的想法是我的部分id与菜单link的href值相同(这是一个锚书签),所以我的逻辑是:比较section idnav a href 值,如果它们匹配 addClass .active 到此菜单 link。我怎样才能实现这个逻辑?

a- 如何获取 nav 中所有 link 的 href

b- 我如何将它与 section idaddClass 与匹配的导航 link 进行比较?

我的 html 看起来像这样:

<nav>
 <a id="b1" href="#landing">Home</a>
 <a id="b2" href="#portfolio">Portfolio</a>
 <a id="b3" href="#experience">Experience</a>
 <a id="b4" href="#about">About</a>
</nav>

<section id="landing">some content</section>
<section id="portfolio">some content</section>
<section id="experience">some content</section>
<section id="about">some content</section>

而我目前的 jQuery 看起来像这样

$('#landing').waypoint(function(direction) {
  if (direction === 'down') {
    $('nav a').removeClass('active-nav');
    $('#b1').addClass('active-nav');
  }
}, {
  offset: '25%'
});

$('#landing').waypoint(function(direction) {
  if (direction === 'up') {
    $('nav a').removeClass('active-nav');
    $('#b1').addClass('active-nav');
  }
}, {
  offset: '-25%'
});

效果很好,但必须对每个部分单独重复。

您可以像这样使用 section 选择器,而不是使用每个部分的 id 和附加处理程序:

// this event is called for all sections.
$('section').waypoint(function(direction) {
  if (direction === 'down') {
    $('nav a').removeClass('active-nav');

    // form the selector dynamically.
    // "this" keyword refers waypoint object and the element is located at "this.element"
    // using "this.element.id", get the nav anchor you want to target
    // example: "nav a[href='#landing']"

    var selector = "nav a[href='#" + this.element.id + "']"; 
    $(selector).addClass('active-nav');
  }
}, {
  offset: '25%'
});

$('section').waypoint(function(direction) {
  if (direction === 'up') {
    $('nav a').removeClass('active-nav');
    var selector = "nav a[href='#" + this.element.id + "']"; 
    $(selector).addClass('active-nav');
  }
}, {
  offset: '-25%'
});

有多种方法可以获取您想要的目标元素。在你的例子中,由于 sectiona 元素的顺序相同,你可以使用 .index() and eq(n) 重要: 你需要包装你的带有 div 的部分使“index()”起作用。)

// this event is called for all sections.
$('section').waypoint(function(direction) {
  if (direction === 'down') {
    $('nav a').removeClass('active-nav');
    $("nav a").eq($(this.element).index()).addClass('active-nav');
  }
}, {
  offset: '25%'
});

我为第二种方法创建了一个fiddle。测试一下然后告诉我。