Create .click triggers inside a for loop

0

I have the following code:

$(document).ready(function(){

  console.log($("body").find("form label input")); //da un objeto, una lista, con los diferentes inputs dentro del label dentro del form

  for (var i = 0; i < $("body").find("form label input").length; i++) {

    console.log($("body").find("form label input")[i]); //repite cada uno de los objetos seleccionados por orden
    $("body").find("form label input")[i].click(function(){ //parece ignorar la creación del disparador o eventListener.
      alert("¿hola?"); //no se ejecuta el alert
    });

  }

}

Why is not an eventListener created for each input in each loop repeat? I do not understand ...

    
asked by Adrià Fàbrega 28.04.2017 в 00:46
source

2 answers

1

With jQuery it's very easy, you just have to identify which elements you want to click on and assign them to the jQuery selectors that are the same as CSS.

This way you avoid going through the DOM objects because when you go through them you also go through the functions and other methods that you have, that means you would consume less PC resources.

        $(function(){
            //Agrega el evento click a todos los elementos que tengan la clase "item"
            $(".item").on("click", function( a ){
                alert( "Hola: "+$(a.currentTarget).html())
            })
        })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="item"> Click me 1 </li>
<li class="item"> Click me 2 </li>
<li class="item"> Click me 3 </li>
    
answered by 28.04.2017 / 06:00
source
1

You can create a Listener directly from JavaScript . via addEventListener () as follows:

var inputs = $("body").find("form label input");
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener("click", function(){
        alert(this.name);
    });
}

Although from Jquery it would have been enough with

$(document).on('click', 'form label input', function(event) {
    /* Acciones a Realizar después del Evento Click */
});
    
answered by 28.04.2017 в 01:00