Reputation: 4921
I have a number of div
s in my HTML file that are dynamically generated. When I add the div
s, I want to add an onclick
event to each div
.
Each div
has a dynamic id
. Using id
, how can add an onclick
handler?
Code that generates div
s:
function createSlider(resp) {
$.each(resp, function(key, val) {
var item = "<div class='item' id="+val.id+">";
item += "<h2>" + val.category + "</h2>";
item += "<img src=" + val.image + " alt=" + val.title + ">";
item += "</div>";
$(".content-conveyor").append(item);
});
}
Upvotes: 3
Views: 17364
Reputation: 2348
.live() is used to attach handlers to DOM elements that may not yet exist in the DOM.
After $(".content-conveyor").append($item);
add following code.
$('#' + val.id).live(click,function() {
// your code here
});
Upvotes: 1
Reputation: 13292
You can apply the click function to the ID after you append it to the dom. So, after your $(".content-conveyor").append(item);
line, add this:
$('#' + val.id).click(function() {
// Do stuff on click
});
function createSlider(resp) {
$.each(resp, function(key, val) {
var item = "<div class='item' id="+val.id+">";
item += "<h2>" + val.category + "</h2>";
item += "<img src=" + val.image + " alt=" + val.title + ">";
item += "</div>";
var $item = $(item).click(function() {
// Add on click code here
});
$(".content-conveyor").append($item);
});
}
This would attach the click callback without having to use the ID at all.
Upvotes: 7
Reputation: 311
You could use the class name of the div for an event handler on all elements that match that class name.
$(".item").click(function() {
//
});
Upvotes: 1