JQuery click event in .class selector

5

I created several div using jQuery where I assign them to the CSS class numero :

for(...)
textoHTML += "<div class='numero par'>"+sorteado+"</div> <!-- numero par-->\n";
...
textoHTML += "<div class='numero impar'>"+sorteado+"</div> <!-- numero ímpar-->\n";
$( "#quadro" ).html(textoHTML);

I want to be able to click on this div and retrieve the number drawn. But I still do not know how to do it, is it with innerHtml ? this ?

However, it looks like the mouse click event is not working:

$( "numero" ).click(function() {
   console.log("Clicou no número");
});

With the above code nothing happens. Can it have something to do with the fact that the CSS class numero of div is not originally in the DOM?

    
asked by anonymous 28.02.2014 / 05:08

2 answers

9

Your intuition was correct, it is using this and innerHTML .

What's missing:

  • Need a point in the jQuery selector for classes

        '.numero'
         ↑
    (ponto aqui)
    
  • Dynamically created elements need be delegated in case you are tying the .click() before the for cycle has run.

    If you are not tying the .click() before the for cycle has run, you can use click as you have in the question, joining the point to the CSS class.

    $('#quadro').on('click', '.numero', function () {
    
  • You can use this within the function click

  • You can use this.innerHTML within the function.

    Here it is missing a parseInt() to convert the string to a number in case you want to use that value as a number. If it is just for show and you do not need to make calculations with the number then you can use only var numero = this.innerHTML; or even innerText , instead of innerHTML .

  • Example can be seen here :

    var textoHTML = '';
    for (var sorteado = 0; sorteado < 30; sorteado = sorteado + 2) {
      textoHTML += "<div class='numero par'>" + sorteado + "</div> <!-- numero par-->\n";
      textoHTML += "<div class='numero impar'>" + (sorteado + 1) + "</div> <!-- numero ímpar-->\n";
    }
    $("#quadro").html(textoHTML);
    
    $('#quadro').on('click', '.numero', function () {
      var numero = parseInt(this.innerHTML);
      alert(numero);
    });
    
        
    28.02.2014 / 09:00
    4

    If you have issues with elements that were not originally in the DOM, you can use the .on () method of jQuery . Example:

    $( ".numero" ).on( "click", function() {
        //codigo
    });
    

    Until a while ago the .live () method was used for this, but this is already obsolete.

        
    28.02.2014 / 05:58