I have the following HTML element:
<a href='#' class='receipt' id='{some id. generated dynamically}'>Receipt</a>
I have the following jQuery, to handle a click:
$('.receipt').click(function () {
alert('hai');
alert($(this).attr('id'));
});
For some reason, when I click….nothing happens. I originally was trying to use mouseover, but I thought I was doing it incorrectly so I tried click. No dice..am I missing something here?
UPDATE – This is how it ended up working, I’m using .live over .on as Jeff B suggested, but I’m sure .on would work just as well.
$('.receipt').live('click', function () {
alert('hai');
alert($(this).attr('id'));
});
UPDATE 2 – .on will be replacing .live in the future, so you should probably use .on.
You mention that the id is generated dynamically. If the element is created after the handler is created, it will not work.
For dynamic elements, use
.on():In this case,
bodyis the element that essentially handles the click, once the event travels up the DOM, and then it makes sure it originated in.receipt. Instead ofbody, you could use any element that is a parent/ancestor of the.receiptdivs, preferably closer.Because
bodyhandles the click, the handler is attached to something that always exists. This way you can add and remove.receiptelements without worrying about the handler disappearing.