event with jquery

Asked

Viewed 117 times

2

In Html we have:

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

No js temo:

 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 doesn’t work , how can I do something like this?

  • The code you put here works perfectly: https://jsfiddle.net/dks20s7s/ Your real problem is not described here. Please adapt jsFiddle to show your problem.

  • Joy Peter can [Dit] the question and explain the problem better?

  • What you need is to transfer the event click to the divsubsequent s to then perform some action on each of them, right?

  • yes that’s right.

2 answers

3

Answer edited after question changed:

One way to resolve this is to record dynamic events. Within your defined click you record the click for the dynamically named element. That may be enough or not, depending on your case.

If 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>
<div id="elemento">clique</div>
<div id="elemento1">el1</div>
<div id="elemento2">el2</div>
<div id="elemento3">el3</div>

3


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

A suggestion is at the time of the event to verify which was the this, or e.target and compare your ID to know what the function should do.

Something like that:

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: https://jsfiddle.net/7b7c3e8c/

Browser other questions tagged

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