views:

147

answers:

3

I have a <ul> tag that I want to append some <li> tags inside. Example:

$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append('<li id='a'>a</li>');
$('#myUL').append('<li id='b'>b</li>');

I want to give every <li> a different click event. How can I accomplish that?

+3  A: 

Try something like this:

$('<ul></ul>')
    .attr('id', 'myUL')
    .append(
        $('<li>a</li>').click(function() {
            alert('First one clicked');
        })
    )
    .append(
        $('<li>b</li>').click(function() {
            alert('Second one clicked');
        })
    )
    .appendTo('body')
;
nickf
+1  A: 
var firstLi = $('<li id='a'>a</li>');
firstLi.click(function() { ... });
$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append(firstLi);
$('#myUL').append('<li id='b'>b</li>');
Frank Schwieterman
A: 

Can't you just put some marker on the list item and give them all the same event? Or, better yet, use a live() event and then you don't even need to add one:

$('#myUL').append('<li id='a'>a</li>');

with:

$(function() {
  $("#myUL li").live("click", function() {
    if (this.id == "a") {
      ...
    }
  });
});

Otherwise just reverse the order and the syntax is much nicer:

$"<li></li>").attr("id", "a").text("a").appendTo("#myUL").click(function() {
  ...
});

You could simply do this:

$"<li id='" + a + "'>" + a + "</li>")..appendTo("#myUL").click(function() {
  ...
});

but I don't recommend this when dealing with dynamic input because you may not properly escape special characters whereas calling attr() and text() will correctly escape content and make you less susceptible to XSS exploits.

cletus