jQuery counting automatically the ID's

1

So, I've got a scheme here like the FAQ that the site administrator who registers the Faqs. Each new registered question generates two new divs:

<div>Pergunta1</div>
<div>Resposta1</div>

So I use a Jquery to do the toggle effect. When the person clicks on the question it displays the answer:

$(function(){ 
    $('#pergunta1').click(function(){
    $('#respota1').toggle(700);         
});

Only in the media that the question and answer divs are added I have to add jQuery manually.

If you register another:

<div>Pergunta2</div>
<div>Resposta2</div>

Then I would have to do another Jquery shown up there by changing it ...

 $(function(){ 
        $('#pergunta2').click(function(){
        $('#respota2').toggle(700);         
 });

Would it be like jQuery to automate this? Like a while or something?

    
asked by anonymous 08.01.2017 / 16:50

1 answer

0

You have to delegate this event and tell jQuery what to look for.

To delegate the event you have to use an element that already exists, the parent of those divs that are being inserted.

For jQuery to know what to look for you can use a pseudo selector ^= . p>

So the code can be:

$('#elementoPai').on('click', '[id^="pergunta"]', function(){
    var pergunta = this;
    var idResposta = pergunta.id.match(/\d+/)[0];
    var resposta = document.getElementById('resposta_' + idResposta);
    // etc...
});

You can read more about delegation here: link

    
08.01.2017 / 17:22