jQuery counting automating ID’s

Asked

Viewed 33 times

1

So, guys, I have a schematic here like FAQ that the site administrator who registers the Faqs. Each new registered question generates two new Ivs:

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

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

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

Only that on the average 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 changing...

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

Could jQuery automate that? Like a while or something?

  • Can you explain the code that "generates two new Ivs"? It creates Ids in the elements?

  • What is the element where these Divs are inserted? is the same element for all?

  • It’s a while in php that pulls from the bank... and a counter that is in the id.. type: <? php $a = 1; while(...){ ? > <div id="question<? php echo $a? >"></div>"; <? php $a++; } };?>

  • What is the element where these Divs are inserted? is the same element for all?

  • They stay inside a box with another div

  • Okay, so you can delegate the event, so it’s simple. Can you [Edit] the question with an example HTML with 2 questions, and what do you want to happen when one is clicked? So it will be simple to answer adjusted to your problem.

  • Actually I need to know how to make jQuery understand that there will always be a new id=question[x] ? Without I need to insert manual, understood ?

  • Exactly, so I say it’s simple. But you need to delegate because these elements don’t exist yet when the page loads.

  • Sorry friend @Sergio I’m new here, but what would delegate?

Show 4 more comments

1 answer

0


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

To delegate the event you need to use an element that already exists, father of these Divs that are being inserted.

For jQuery to know what to look for you can use one pseudo selector ^=.

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: /a/5199/129

  • Top brother I will test here and bring the return! It was worth the strength!

  • @Jaidermasterinfo says if there’s anything you don’t understand. The idea of delegating is because you cannot add event headphones to elements that do not yet exist on the page when Javascript is read.

Browser other questions tagged

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