Reputation: 290
I have a select list input that allow user to select multiple item. Upon selection, it will dynamically create a new li item in my ordered list as in the HTML code below.
HTML
<ol class="asmList3" id="multiol">
<li rel="multioption1" class="asmListItem2" style="height: 20px; ">
<span class="asmListItemLabel2">Acrylic</span>
<a href="#" class="liRemoveItem">X</a>
</li>
</ol>
Script
$('.liRemoveItem').click(function(){
alert("X is clicked");
//remove child li
});
Supposely on clicking on the X
which has the class liRemoveItem
, I wish to remove the child li but the class is not even working for a simple alert. I think it is because the child li was created dynamically.
If the li was added in the HTML when loaded and not dynamically created, the class liRemoveItem
works. Can someone please give me a hint as to what I did wrong? Thank you.
Upvotes: 1
Views: 1276
Reputation: 21376
Try using this
$('.liRemoveItem').live('click', function() {
alert("X is clicked");
//remove child li
});
Upvotes: 3
Reputation: 21864
use the jQuery live method
Attach a handler to the event for all elements which match the current selector, now and in the future.
$('.liRemoveItem').live("click",function(){
alert("X is clicked"); //remove child li
});
The .live()
method is able to affect elements that have not yet been added to the DOM
through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live()
is never bound to an element; instead, .live()
binds a special handler to the root of the DOM tree
Upvotes: 3