Adam Morris
Adam Morris

Reputation: 8545

Append li with a link that has a custom click event

I am trying to append a li element to a list with a link that has custom click event... I am trying something like:

<div id="myid"><ul></ul></div>

$('#myid ul').append("<li><a href=''>Link</a></li>").click(function(){alert('hi')})

But the click event is on the li and not the a href. How do I fix this?

Upvotes: 2

Views: 3192

Answers (4)

Felix Kling
Felix Kling

Reputation: 816334

Actually, the click event handler is bound to the ul element.

How do I fix this?

Bind it to the a element:

$("<li><a href=''>Link</a></li>").find('a').click(function(event) {
    event.preventDefault(); // <-- if you don't want the browser follow the link
    alert('hi');
}).end().appendTo('#myid ul');

DEMO

Creating the link separately might be cleaner though:

$('<a />', {
    text: "Link",
    href: "",
    click: function() {/*...*/}
}).wrap('<li />').parent().appendTo('#myid ul');

Information about the methods used can be found in the jQuery API documentation.

Upvotes: 9

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

$('#myid ul').append("<li><a href=''>Link</a></li>")
     .find("a:last").click(function(){
         alert('hi')
})​​​​;

Upvotes: 0

Rey Gonzales
Rey Gonzales

Reputation: 856

$('#myid ul').append("<li><a href=''>Link</a></li>");

$("a").live("click", function() { // or use on(...)
    alert('hi');
});

Bind the click, on live, to the a element after appending. Jsfiddle here: http://jsfiddle.net/reygonzales/Z5pSC/

Upvotes: 1

Nicol&#225;s Torres
Nicol&#225;s Torres

Reputation: 1345

You could use .on since your li is being appended on the fly

 $('#myid ul').append('<li id="li1"><a href=''>Link</a></li>');

    $('body').on('click','#li1',function(){
         alert('hi');
    });

Upvotes: 1

Related Questions