문제

I am having an issue removing/adding a class to the closest div with a class. Right now it toggles the class for all, and not for the closest.

What am I doing wrong?

$(document).on('click', '.btnMoreInfo', function () { 
$(this).closest('div').find('.moreInfo').toggleClass('hide')
})

HTML:

<ul>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>

도움이 되었습니까?

해결책

One way would be to use jQuery's next() method (assuming your HTML structure always looks like it does above):

$(document).on('click', '.btnMoreInfo', function () { 
  $(this).next('div').toggleClass('hide');
})

jsFiddle example here.

다른 팁

$(this).next('.moreInfo').toggle();

you can also use slideIn and slideOut and toggle

you can use next like

$(this).next('.moreInfo').toggleClass('hide');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top