Applying jQuery .click() to Ajax-generated HTML
ajax, event-handling, jquery
Solution
Depend on your version of jQuery, there are these solution:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
obviously the last one `.on()` is the best choise. More Information.
but about `.bind()`:
As of jQuery 1.7, the `.on()` method is the preferred method for attaching event handlers to a document. For earlier versions, the `.bind()` method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to `.bind()` occurs. Reference
For your problem answer is something like these:
$('.edit-button').on("click",function(){ })
or
$(document).on("click", ".edit-button", function(){ });
Note: Use of the `.live()` method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. More Information
Update `.live()` removed after jQuery 1.9 upgrade
Problem
I'm using jQuery to manage the "Edit" button on comments for an app I'm coding. In my `document.ready`, I have: ``` $('.edit-button').click(function(){ // Code to trigger the editing interface for parent comment }); ``` I'm also using jQuery to display newly-posted comments without refreshing the page. Within the relevant `$.ajax()` function, I write the new comment to the DOM using a `$.before(data)`. Problem is, the `.edit-button`s within `data` don't have the aforementioned `$.click()` applied to them, because that happens in `document.ready`. So I click on them, and nothing happens. I've tried the (extremely ugly) solution of having the Ajax function re-include the .js file in which I call `document.ready`. This works, except it re-applies the `.click()` to every single `.edit-button`, so they open the editing interface twice (or even three times). So, how can I re-apply the `$.click()`s from `document.ready`? Preferably without having to copypasta my `document.ready` function into another javascript file, in case I modify it later.