onclick () on elements generated through ajax?

0

I'm trying to use a onclick event on <li> generated through a ajax() form. I have the following code

$(".option").click(function(){
  alert();
  var text = $(this).attr("href");
  window.location.href=href;
});

In this code, it does not even alert() gives, <li> has that class and even then it does not give a signal.

I would give code information ajax but it is against my client's policy to disclose information so this is the example of the html line he writes.

echo "<li class='option' href='index.php?pg=13&id=1'><small><b>[Texto]</b></small> Nome</li>";
    
asked by anonymous 19.12.2017 / 20:35

2 answers

3

What you can assign to document is a click event in your class, since elements are being generated after DOM has already been loaded, so it will not catch the click event, do as follows:

$(document).on('click', '.option', function(){
  //Evento do click
})

This way you say that whenever you click on document on this classe it executes this method!

Another way is to use jQuery's delegate (), this way you say that in every element (div) in class (option1) it will execute this method

$('div').delegate('.option1','click', function() {
    //Evento do click
});

I added 3 examples separated by a line, check that in the first example with each click it generates an element, but the generated element has no action, already in the second and third examples the generated elements have the desired action:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><divclass="conteudo1">
    <div class="option1" data-option="1">Click1</div>
</div>
<hr>
<div class="conteudo2">
    <div class="option2" data-option="1">Click1</div>
</div>
<hr>
<div class="conteudo3">
    <div class="option3" data-option="1">Click1</div>
</div>
<script>
    $('.option1').on('click', function () {
        var option = $(this).data('option');
        $('.conteudo1').append("<div class='option1' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
    });


    $(document).on('click','.option2', function () {
        var option = $(this).data('option');
        $('.conteudo2').append("<div class='option2' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
    });


   

   $('div').delegate('.option3', 'click', function(){
        var option = $(this).data('option');
        $('.conteudo3').append("<div class='option3' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
   })
 </script>
    
19.12.2017 / 20:45
1

For elements like this generated from javascript you will need to use .on()

$(".option").on("click", function(){
  alert();
  var text = $(this).attr("href");
  window.location.href=href;
});
    
19.12.2017 / 20:38