I have an unordered list. When the user clicks on an item it calls a function. I used the $(document).ready() event to bind the function to the list items.
The problem I have is that the contents of the list are replaced from time to time using the $('#list').html() method (using AJAX). This means that the binding on each item is lost.
I tried binding the function to the list (instead of the items). This works fine except that this is then a reference to the list, not the clicked item, and I am using this in my function.
The options I see are:
- After the contents of the list are reloaded, re-bind the function to each item. This seems to me like a lot of work for the browser to have to do.
- Bind the function to the list (not the list items), and work out how to reference the clicked list item from there.
Which would you use? How? Is there a better way?
Thanks!
The second point you mentioned is called event delegation and would be a good solution here. Fortunately, jQuery makes event delegation very easy:
jQuery figures out the reference for you, i.e. inside the event handler
thiswill refer to thelielement that was clicked (the element that matches the second selector.Read more about direct and delegated event handling with jQuery.