문제

I hope this isn't confusing. I have two lists:

<ul class="list_A">
  <li class="item_1"></li>
  <li class="item_2"></li>
  <li class="item_3"></li>
</ul>

<ul class="list_B">
  <li class="item_1"></li>
  <li class="item_2"></li>
  <li class="item_3"></li>
</ul>

What I'm trying to figure out is when I hover over one of the list items, I want to have the list item with the same class in the other list have the same 'active' class appended to it. Which is what I can do with the below code.

jQuery(document).ready(function($){
  $(".item_1").hover(function () {
    $(".item_1").toggleClass('active');
  });
  $(".item_2").hover(function () {
    $(".item_2").toggleClass('active');
  });
  $(".item_2").hover(function () {
    $(".item_2").toggleClass('active');
  });
});

However, how do I make it so I just have it find the appropriate class without having to duplicate the code for each and have it something like the below? The below doesn't work. :(

jQuery(document).ready(function ($) {
  var i = 0;
  i++;
  $(".item_" + i).hover(function () {
    $(".item_" + i).toggleClass('active');
  });
});
도움이 되었습니까?

해결책

You need to use the mouseenter and the mouseleave events instead of hover, or else it will trigger every time you mouse moves over the element. And the toggle will trigger all the time.

This should work fine:

jQuery(document).ready(function() {
    jQuery('li').mouseenter(function() {
        jQuery('.'+this.classList[0]).addClass('active');
    }).mouseleave(function() {
        jQuery('.'+this.classList[0]).removeClass('active');
    });
});

Here's the FIDDLE

EDIT: If you want to apply this to only specific lists, add a common class to each ul and update the first selector, like jQuery('ul.myclass > li')

다른 팁

You should use it like that :

jQuery(document).ready(function ($) {
    for ( var i = 1; i < 4; i++ ) {
        $(".item_" + i).hover(function () {
            $(".item_" + i).toggleClass('active');
        });
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top