Event onClick is not working!

Asked

Viewed 639 times

0

Event $('.target').on('click', function(){}) on a button I’m holding via ajax, but it doesn’t work, I believe it’s because the content isn’t loaded on the page yet, so.target doesn’t exist when the page loads.

Can someone help me?

Follows 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);
      })
  });
  • 4

    Could you put the part of html which contains the element? I believe it would facilitate understanding of your question...

2 answers

3


Quick response

You can attach the event to a parent element that is fixed in HTML. This way, you don’t need to give the bind to the dynamically created elements.

In the example below, I am creating buttons dynamically that already have the onclick, because the same is configured 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>

<ul id="lista">
  <li>
    <button class="bsseguir">Seguir</button>
  </li>
</ul>

But... why does it happen?

According to jQuery’s own documentation,

Event handlers are bound only to the Currently Selected Elements; they must exist at the time your code makes 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.

The events are attached only for selected items that exist in DOM the moment you call the method .on(). To ensure that these elements are present at the time of the call, you can place the script after the markups HTML or use the document.ready to await all loading of the DOM. However, this is not the reality of elements created dynamically, where you can use delegated Events alternatively.

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

  • 1

    I think the great answer just corrects that it’s not $("#menu") and yes $("#lista"), but still it is ok the explanation.

  • Hadn’t seen the #list, updating the reply...

  • 1

    He killed Vinicius... Thank you very much for the answer. It’s already solved!

  • @Filiperodrigues that good! If you solved your problem, mark the answer as correct by clicking on the V below her points (:

1

In your case, just enter the 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');
      });
  })
});

An unnamed technical resource (alias gambiarra) 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
});

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

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

    Wouldn’t it be better to teach them to use promises instead of gambiarras?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.