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.
Could you put the part of
html
which contains the element? I believe it would facilitate understanding of your question...– JcSaint