Browse a list with each in Jquery

Asked

Viewed 68 times

0

I’m having trouble individually opening each option on that list to show the corresponding information for each item

HTML

<ul class="lista">
      <li class="item">
           <strong>Item 1</strong>
           <div class="texto">
              <p>Descrição do item 1...</p>
           </div>
      </li>
      <li class="item">
           <strong>Item 2</strong>
           <div class="texto">
              <p>Descrição do item 2...</p>
           </div>
      </li>
      <li class="item">
           <strong>Item 3</strong>
           <div class="texto">
              <p>Descrição do item 3...</p>
           </div>
      </li>
</ul>

Javascript

$(document).ready(function(){
      $('div.texto').hide() // ocultando a descrição dos itens
      $('li.item').each(function(){ // percorrendo cada elemento da lista
             this.click(function(){ // cada vez que clico em um elemento da lista é lançado uma função
             $('div.texto').toggle() // o texto é mostrado ou ocultado novamente
    })
  })
})

I’m using the version of Jquery 3.2.1

PS: As far as I understand from the comments, my code is doing this, which information is missing so that the function actually runs correctly.

  • 2

    When handling the event click of the element li.item you do $('div.texto').toggle(). How would jQuery know about which element div.texto should it act? How is a child element of the <li>, then you can reduce your search of the elements to only child elements. You can search for the function children jQuery

1 answer

0

No need to call the function each().

The simplest would be to call the function $('.lista .item').click() that monitors by clicks on all <li class="item">.

See in the code below:

    $(document).ready(function(){
        $('div.texto').hide() // ocultando a descrição dos itens

        $('.lista .item').click(function(){
            //Ocultar se houver alguma descrição anterior sendo exibida:
            $('div.texto').hide();

            //Buscar a tag com class="texto" filha do item clicado e exibi-la:
            $(this).find('.texto').show();
        });
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<ul class="lista">
      <li class="item">
           <strong>Item 1</strong>
           <div class="texto">
              <p>Descrição do item 1...</p>
           </div>
      </li>
      <li class="item">
           <strong>Item 2</strong>
           <div class="texto">
              <p>Descrição do item 2...</p>
           </div>
      </li>
      <li class="item">
           <strong>Item 3</strong>
           <div class="texto">
              <p>Descrição do item 3...</p>
           </div>
      </li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.