vendredi 3 août 2018

Event on (); duplicate the click () event; in jQuery in dynamically loaded element

Good afternoon I have a question that I have not been able to solve, I am using jQuer in one of my projects and I am loading a part with ajax, well any event within the DOM works well, the problem arises when I execute an event to an element that was loaded via ajax good an example.

$('element').click(function(){ /*funcion a ejecutar.*/  });

The problem:

(function($){
     $(document).ready(function(){
          $(document).on('click','elemento',function(){
                /* funcion a ejecutar*/
             });
        });
})(jQuery);

The problem is that when I click on "element" with the method on (); the action is executed twice, this I found out when I placed a counter so that the action could be executed only once.

 (function($){
     $(document).ready(function(){
      var inicio=0;
        $(document).on('click','elemento',function(){
          if( inicio == 0){ 
             /*funcion a ejecutar*/
             inicio++ /*cambio inicio para que solamente se ejecute una vez*/
          }
       });
    });
})(jQuery);

Well with this you can solve the problem when you make a single click the problem is that this function was to work for different elements with the same class.

Someone can tell me where the error is in my code snippet or a better way to use click () with on (), or a different way to access elements that were created dynamically.

Thank you.




Aucun commentaire:

Enregistrer un commentaire