Reputation: 5114
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
Reputation: 31043
you can delegate click event to #cityList
$("#cityList").delegate("div","click",function(e){
//handler code here
});
Upvotes: 0
Reputation: 6514
I recommend that you use the .live() function, which lets you bind events even to elements that are added later dynamically.
Upvotes: 0
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