Suppose you want to dynamically add to a HTML menu, where the menu HTML will look like-so:
<ul>
<li><a href="#">item-1</a>
<li><a href="#">item-2</a>
</ul>
And each element has a "click" event bound to it by. How does one create this dynamically with jQuery?
What'd I'd like is the equivalent of the following (with hypothetical menu_item array of objects with 'title's):
$('menu').append("<ul>");
for (var index in menu_items) {
$('menu').append("<li><a href='#'>"+menu_item['title']+"</a>")
.live("click", function(e) { /* Event Handler */ });
}
$('menu').append("</ul>");
Unfortunately this won't work for two reasons (at least, that I'm aware of):
- the .live() element matches only the most recent element inserted.
I'd appreciate insight into how one may solve this problem with jQuery. I'd prefer to do this without cluttering up my ID namespace, if that's possible.
EDIT:
Two clarifications (in case it's not obvious):
The < ul > doesn't exist to start with.
Information from menu_item is used in the function (i.e. .live('click', function(e) { /* do_something_with ... */ menu_item['info'] } ).