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

How to match the index of two anchors within two rows using jQuery?

本文关键字:两个 索引 两行 jQuery 何使用      更新时间:2023-09-26

我有一个带有两行链接的容器。我需要向链接到同一位置的两个链接添加一个 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>

如果你想要索引,你可以使用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');
    }
});

小提琴

试试这个:

$('.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');
    }
  });
});

和更新的小提琴

你快到了。

更新了您的小提琴 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,但对于这个特定问题,我认为这是您的解决方案。

希望这有帮助,干杯。