I have the following that is created dynamically:
<a class="editLink" href="/location/Edit?city=05">Edit</a>
This and other editLink rows are created dynamically.
What I would like to do is add some jQuery to these:
$(".editLink").button();
$(".editLink").click(function () {
alert('edit link');
return false;
});
Is there some way I can assign this BEFORE the elements appear? Also how can I deal with the following:
$(".editLink").button();
When the .editLink is not already there.
Use event delegation, by putting the handler on the document.
This is called “live” or “delegated” events. The
$(document)part identifies the element that will handle the event, this one must exist when this code is run. You should set this to a parent element as far down as you can. Usingdocumentis a bit overzealous, but it will work.The
'.editLink'string identifies a selector for any child elements inside the element with the handler. When the event happens the original element is checked against this selector to see if something matching fired the event. And if so, then run the event handler.See working example here: http://jsfiddle.net/Squeegy/guz9A/1/
Note how the links are not present when the handler is bound, but they still trigger the handler when they are added later on.