OnClick event is not working! [duplicate]

0

Event $('.target').on('click', function(){}) on a button I am loading via ajax , but it does not work, I believe it is because the content is not yet loaded on the page, so the '.target' does not exist when the page loads.

Can anyone help me?

Follow the code:

$(".bseguir").on('click',function(){
    alert('oi');
});


$.getJSON('pagina.php',function(data){
      $.each(data,function(){
          html = '<li class="qf b aml">\
                  <button class="bseguir" id="">Seguir</button>\
                  </li>';

          $('#lista').append(html);
      })
  });
    
asked by anonymous 06.12.2016 / 12:53

2 answers

3

Quick response

You can attach the event to a parent element that is fixed in the HTML. That way, you do not have to bind to dynamically created elements.

In the example below, I am creating buttons dynamically that already have onclick , because it is set for all children of #lista with class .bsseguir ,

$("#lista").on("click", ".bsseguir", function() {
  $("#lista")
    .append($("<li>")
      .append($('<button>')
        .attr('class', 'bsseguir')
        .append("Seguir")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="lista">
  <li>
    <button class="bsseguir">Seguir</button>
  </li>
</ul>

But ... why does this happen?

According to jQuery's own documentation,

  

Event handlers are bound to the currently selected elements; they   you must make the call to .on (). To ensure   the elements are present and can be selected, place scripts after the   elements in the HTML markup or perform event binding inside a document   ready handler. Alternatively, use delegated events to attach event   handlers.

Events are appended only for selected elements that exist in DOM at the time you call the .on() method. To ensure that these elements are present at the time of the call, you can either put the script after HTML tags or use document.ready to wait for full DOM loading. However, this is not the reality of dynamically created elements, where you can use delegated events as an alternative.

And the Delegated Event is what we built in the previous example, where an event is appended to an existing parent element in the .on() execution, also reporting a selector responsible for the trigger that will trigger this event. In addition to the ease with dynamic elements, you'll be creating just one event that can be triggered by multiple elements, causing less overhead than creating an event for each element that can trigger it.

    
06.12.2016 / 13:31
1

In your case, just enter bind in the sequence:

$.getJSON('pagina.php',function(data){
  $.each(data,function(){
      html = '<li class="qf b aml">\
              <button class="bseguir" id="">Seguir</button>\
              </li>';

      $('#lista').append(html);
      $(".bseguir").on('click',function(){
        alert('oi');
      });
  })
});

A technical resource not cataloged (vulgo gambiarra) that you can use is:

$(function(){
    window.setTimeout(function(){
        $('.target').on('click', function(){});
    }, 2000); //Aqui você regula um tempo seguro em que o botão já estará carregado
});

Since ajax does not run automatically, depending on some action, I advise you to put the code in success of ajax :

$.ajax({
    url: "...",
    success: function(data){
        //...
        //após inserir seu código, você atrela o evento
        $('.target').on('click', function(){});
    }
});
    
06.12.2016 / 13:06