Reputation: 14844
I know that similar questions are being asked (like here) but, being a jQuery noob, I still can not attach a click listener to an a
element within a li
where the whole ul.li.a
is dynamically appended to the DOM like this.
<div id="users-col">
<!-- dynamically appended -->
<ul id="users-list">
<li>
<a class="user" id="Alice">Alice</a>
</li>
<li>
<a class="user" id="Bob">Bob</a>
</li>
</ul>
<!-- END dynamically appended -->
</div>
Here is a (one of the many) jQuery functions that I have tried:
$('#users-col ul.li.a').on('click', '.user', (function () {
console.log('user clicked:', this.id);
});
How can I fix this?
Upvotes: 1
Views: 131
Reputation: 782
For convenience sake and reuse, I leave the first field just directly tied to the document:
$(document).on('click', '.user', (function () {
console.log('user clicked:', this.id);
}));
<div id="users-col">
<!-- dynamically appended -->
<ul id="users-list">
<li>
<a class="user" id="Alice">Alice</a>
</li>
<li>
<a class="user" id="Bob">Bob</a>
</li>
</ul>
<!-- END dynamically appended -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
The listener is directly tied to the document vice the class, so now it is very easy to reuse this class dynamically across your entire document.
Upvotes: 0
Reputation: 790
in such case you must hook an event with parent of dynamically created children:
$('#users-col').on('click', 'a.user', (function () {
console.log('click bound');
});
Upvotes: 0
Reputation: 28455
You need to bind the event on element that is available (not added dynamically)
$('#users-col').on('click', 'a.user', (function () {
console.log('user clicked:', this.id);
});
For reference, jQuery.on
Upvotes: 5