event with jquery

2

In Html we have:

<div id="t1" > </div>
<div id="t2" > </div>
<div id="t3" > </div>

I'm not afraid:

 var aux="#t";
 var count=0;

 $(document).ready(function(){
       $("#t1").click(function(){  
              count=count+1;
              aux = aux.concat(count.toString()); 

        });



       $(aux ).click(function(){  

              alert("Hello!!!"); 
        });
 });

In the second click it does not work, how can I do something like this?

    
asked by anonymous 17.11.2016 / 02:37

2 answers

3

When the browser reads $(aux).click(function() { it will no longer look for changes in the variable aux , after the moment the page loads. You have to change logic.

One suggestion at the time of the event is to check what this , or e.target is, and compare your ID to what the function should do.

Something like this:

var count = 0;
$(document).ready(function() {
    $('[id^="t"]').click(function() {
        if (this.id == 't1') count++;
       alert('O id da div clicada é: ' + this.id + '\nE o valor de count é: ' + count);
    });
});

jsFiddle: link

    
17.11.2016 / 15:37
3

Edited response after question changed:

One way to resolve this is to log dynamic events. Within your defined click you register the click for the element with dynamic name. That may or may not be enough, it depends on your case.

If it is not, within the click you trigger an event for that element and reference that event later. Example:

var elem = '#elemento',
    event1 = 'fire1',
    event2 = 'fire2',
    event3 = 'fire3',
    count = 0;

// registra o clique pro primeiro elemento
$(elem).click(function() {
  count++;
  
  // registra o clique pros outros elementos em ordem
  $('body').on('click', elem+count, function() {
    // se necessário, dispara um novo evento
    $(this).trigger('fire'+count);
  });
  console.log('trigger registrado para o elemento '+count);
});

// Usando os eventos criados 
// Só disparam depois que clicar X vezes no primeiro elemento, ativando cada um
$('body').on(event1, function(e) {
  console.log('clique dinamico no elemento 1');
});

$('body').on(event2, function(e) {
  console.log('clique dinamico no elemento 2');
});

$('body').on(event3, function(e) {
  console.log('clique dinamico no elemento 3');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="elemento">clique</div>
<div id="elemento1">el1</div>
<div id="elemento2">el2</div>
<div id="elemento3">el3</div>
    
17.11.2016 / 02:40