JQuery Toggle does not work

1

I'm using the toggle function of jQuery , it's working perfectly, however I put 12 divs with text and when I click open only one, all are opening.

Follow the JavaScript code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>$(document).ready(function(){$("span.seta-baixo").click(function(){
        $("p.perguntas-conteudo").toggle();
    });
});

</script>

What I want is the following when I click on a div , it will expand the text only from it and when I open the other div with other text information , will close the previous one and open only this one.

What is happening is that by clicking the button to open the text, it opens all the div , ie the toggle is catching on all. >     

asked by anonymous 01.11.2018 / 01:25

1 answer

0

You can get the index of the class of the arrow clicked and apply .toggle to its index of class .perguntas-conteudo , since each arrow corresponds to a p , so each index of class of arrow .seta-baixo corresponds at the same index as the class of p .perguntas-conteudo :

$(document).ready(function(){
    $("span.seta-baixo").click(function(){
        // pega o índice da seta clicada dentro da classe
        var idx = $(this).index(".seta-baixo");
        // pega o respectivo <p> pelo índice usando :eq
        var per = $("p.perguntas-conteudo:eq("+idx+")");
        // oculta todos os <p> visíveis exceto o relacionado à seta clicada
        $("p.perguntas-conteudo:visible").not(per).hide();
        // abre ou esconde o respectivo <p> da seta
        per.toggle();
    });
});
.seta-baixo{
   display: block;
}

.perguntas-conteudo{
   display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><spanclass="seta-baixo"><strong>Seta 1</strong></span>
   <p class="perguntas-conteudo">pergunta 1</p>
   <span class="seta-baixo"><strong>Seta 2</strong></span>
   <p class="perguntas-conteudo">pergunta 2</p>
</div>
    
01.11.2018 / 01:47