Read some other things on here re: this similar problem but am not sure how to apply this to my dilemma.
I have a jquery function that replaces some HTML in a list.. For example, before the function runs:
<ul id="mylist">
<li id="item1">blah blah blah</li>
<li id="item2">blah blah blah</li>
<li id="item3">blah blah blah</li>
</ul>
Then I have another which runs on click of the LI e.g:
$("#mylist li").click(function () {
alert($(this).attr("id"));
});
Works fine until I dynamically modify the #mylist html, where the alert is blank.
How can I replace the #mylist html and still be able to select the li's found within?
Read some other things on here re: this similar problem but am not sure how to apply this to my dilemma.
I have a jquery function that replaces some HTML in a list.. For example, before the function runs:
<ul id="mylist">
<li id="item1">blah blah blah</li>
<li id="item2">blah blah blah</li>
<li id="item3">blah blah blah</li>
</ul>
Then I have another which runs on click of the LI e.g:
$("#mylist li").click(function () {
alert($(this).attr("id"));
});
Works fine until I dynamically modify the #mylist html, where the alert is blank.
How can I replace the #mylist html and still be able to select the li's found within?
Share Improve this question edited May 20, 2012 at 2:00 Sampson 269k76 gold badges545 silver badges568 bronze badges asked Dec 29, 2009 at 2:33 JeffJeff 331 silver badge3 bronze badges 2- This might be a silly question but: when you dynamically add LI elements to UL are you specifying an id for them? – leepowers Commented Dec 29, 2009 at 2:37
- Wele to StackOverflow, Jeff! – Sampson Commented Dec 29, 2009 at 2:38
2 Answers
Reset to default 6To maintain this functionality on all future dynamically-added list items, you should use event delegation with $.on()
:
$("#mylist").on("click", "li", function(){
alert( this.id );
});
Read more about $.on()
, online at http://api.jquery./on/.
When you replace the contents of #mylist
you also remove any event handles that were previously attached to its child li
elements.
Instead of the normal click
function, try using jQuery's live function:
$("#mylist li").live("click", function() {
alert($(this).attr("id"));
});
Please note that live
events work a bit differently than traditional event, especially when it es to bubbling and event canceling. If this is a problem, then make sure you reattach click events after you manipulate #mylist
.
You might also consider using event delegation. Here's a quick example:
$("#mylist").click(function(e) {
alert($(e.target).closest("li").attr("id"));
});