I'm a jQuery beginner. I'm adding a bunch of new images into a div. I'd like each of these images to respond to a click.
My initial, and in hindsight foolish code, looked like this:
for (var i = 0; i < 10; i++) {
$("div#stargrid").append("<img class='clickme' src='http://placehold.it/90x90' alt='90x90 placeholder image' />").click(my_event_handler);
}
Now, I've worked out that that's dumb, because the chaining doesn't work how I thought it did, so (I think) that actually adds the click event handler ten times to my div#stargrid
, not once to each img
.
I found one solution that seems to work for me, just to separate these operations out and bind the click event to all the images afterward:
for (var i = 0; i < 3; i++) {
$("div#stargrid").append("<img class='clickme' src='http://placehold.it/90x90' alt='90x90 placeholder image' />");
}
$(".clickme").click(imageclick);
My question is: is that the "right" way to do it?
I realise this may be subjective, but what I'm looking for here is the "standard" way to do this kind of thing in jQuery, preferably with some reasoning as to why it's a good way. I had a look around and couldn't find much in the way of examples of doing what I'm doing here.
Thanks!