如何使用jQuery匹配两行内两个锚点的索引?

时间:2016-02-26 15:22:52

标签: javascript jquery jquery-selectors

我有一个包含两行链接的容器。我需要在链接到同一个地方的两个链接上添加一个nav_link--hover类,在父div中也有相同的索引号。

如何更新以使用索引号匹配两个锚点而不是仅在容器索引中找到的第一个锚点?

例如,如果我将鼠标悬停在第四个链接上,我希望将nav_link--hover类应用于第二个链接(第一行)和第二个链接(第二行)。

JSFiddle

<nav class="nav_container">
  <div class="row-one">
    <a href="#a" class="nav_link">
      <div class="nav_image sprite-cat"><img></div>
    </a>
    <a href="#b" class="nav_link">
      <div class="nav_image sprite-cat2"><img></div>
    </a>
  </div>
  <div class="row-two">
    <a href="#a" class="nav_link">
      <div class="nav_text">Item One</div>
    </a>
    <a href="#b" class="nav_link">
      <div class="nav_text">Item Two</div>
    </a>
  </div>
</nav>

<script>
var $container = $('.nav_container');

$('.nav_link').each(function(i) {
  $(this).on({
    mouseover: function() {
      $container.find('.nav_link').eq(i).addClass('nav_link--hover');
    },
    mouseout:  function() {
      $container.find('.nav_link').eq(i).removeClass('nav_link--hover');
    }
  });
});
</script>

3 个答案:

答案 0 :(得分:3)

如果您想要索引,可以使用index()nth_child来定位该索引的所有子项等。

var $container = $('.nav_container');

$('.nav_link').on({
    mouseenter: function() {
        $('.nav_link:nth-child(' + ($(this).index() + 1) + ')').addClass('nav_link--hover');
    },
    mouseleave:  function() {
      $('.nav_link:nth-child(' + ($(this).index() + 1) + ')').removeClass('nav_link--hover');
    }
});

FIDDLE

答案 1 :(得分:1)

试试这个:

$('.nav_link').each(function(i) {
  $(this).on({
    mouseover: function() {
      // get the href link
      var link = $(this).prop('href');
      //get the anchor
      var hash = link.substring(link.indexOf("#")+1);
      // find all the a tags with href = #anchor, and add css class
      $("a[href='#"+hash+"']").addClass('nav_link--hover');
    },
    mouseout:  function() {
      var link = $(this).prop('href');
      var hash = link.substring(link.indexOf("#")+1);
      $("a[href='#"+hash+"']").removeClass('nav_link--hover');
    }
  });
});

updated fiddle

答案 2 :(得分:0)

你快到了。

更新了您的小提琴https://jsfiddle.net/qxatn2d1/

$('.nav_link').each(function(i) {
  $(this).on({
    mouseover: function() {
      $('a[href="'+ $(this).attr('href') +'"]').addClass('nav_link--hover');
    },
    mouseout:  function() {
        $('a[href="'+ $(this).attr('href') +'"]').removeClass('nav_link--hover');
    }
  });
});

诀窍。它正在寻找具有相同href的所有a元素。我更愿意更改您的HTML,但对于这个具体问题,我认为这是您的解决方案..

希望这有帮助,干杯。