Steven Zack
Steven Zack

Reputation: 5114

jQuery: how to add onlick event to a dynamic generated div?

I want to add a onclick event to a div which generated using folowing code:

$("<div />").attr("city", $(this).attr("city"))
            .attr("state", $(this).attr("state"))
            .html($(this).attr("city") + ',' + $(this).attr("state"))
            .appendTo($('#cityList'));

Should I write onlick event in html()?

Upvotes: 0

Views: 625

Answers (4)

Tim Joyce
Tim Joyce

Reputation: 4517

$('#cityList div').live('click', function(){
    ...do stuff;
});

jQuery Live Link

Upvotes: 0

Rafay
Rafay

Reputation: 31043

you can delegate click event to #cityList

$("#cityList").delegate("div","click",function(e){    
//handler code here
});

http://jsfiddle.net/bXtEz/

Upvotes: 0

Abe
Abe

Reputation: 6514

I recommend that you use the .live() function, which lets you bind events even to elements that are added later dynamically.

http://api.jquery.com/live/

Upvotes: 0

JaredPar
JaredPar

Reputation: 755567

Why not split up the creation of the div and the chaining of the rest of the code. For example

var elem = $('<div />');
elem.click(function () { 
  // Click handler
});

elem.attr("city", $(this).attr("city"))
    .attr("state", $(this).attr("state"))
    .html($(this).attr("city") + ',' + $(this).attr("state"))
    .appendTo($('#cityList'));

Upvotes: 2

Related Questions