You can use the following two jQuery methods:
The first is the .live() method, and the other is the .delegate() method.
Using the first is very simple:
$(document).ready(function() { $("#dynamicElement").live("click", function() {
As you can see, the first argument is the event you want to bind, and the second is the function that processes the event. The way this works is not quite like re-rendering. The general way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a specific event to the DOM element when correctly loading the DOM ( $(document).ready(...) ). Now, obviously, this will not work with dynamically generated elements, because they are not present when loading the DOM.
The .live () path works, instead of attaching the valve handler to the DOM element itself, it attaches it using the document element, taking advantage of the JS and DOM bubbling property (when you click on a dynamically generated element and the event handler is not attached, it continues to look up until it finds it).
Sounds pretty neat, right? But, as I said, there is a small technical problem with this method, it attaches an event handler to the top of the DOM, so when you click on an element, your browser should traverse the entire DOM tree until it finds a suitable event handler. A process that is very inefficient, by the way. And here, where the .delegate() method appears.
Assume the following HTML structure:
<html> <head> ... </head> <body> <div id="links-container"> </div> </body> </html>
So, with the .delegate () method, instead of binding the event handler to the top of the DOM, you can just bind it to the parent DOM element. DOM element are you sure that it will be somewhere from dynamically generated content in the DOM tree. The closer to them, the better it will work. So this should do the magic:
$(document).ready(function() { $("#links-container").delegate("#dynamicElement", "click", function() {
It was a long answer, but I like to explain the theory underlying it, haha.
EDIT: You must correct your markup, this is not valid because: 1) Anchors do not allow the use of the value attribute, and 2) you cannot have 2 or more tags with the same identifier. Try the following:
<a class="removeLineItem" id="delete-1">Delete</a> <a class="removeLineItem" id="delete-2">Delete</a> <a class="removeLineItem" id="delete-3">Delete</a>
And to determine which of these anchors was pressed
$(document).ready(function() { $("#links-container").delegate(".removeLineItem", "click", function() { var anchorClicked = $(this).attr("id"), valueClicked = anchorClicked.split("-")[1]; }); }
With this code, you will save the link identifier in the anchorClicked variable, and the number associated with the anchor in valueClicked.