Domanda

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>

È stato utile?

Soluzione

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.

Altri suggerimenti

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

you can also use slideIn and slideOut and toggle

you can use next like

$(this).next('.moreInfo').toggleClass('hide');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top