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.