JQuery .on('click')仅生效一次:点赞按钮无法重复点击
Hey there! Let's break down why your like buttons are acting up—this is a super common pitfall with dynamic content in jQuery, so we can fix it easily.
What's causing the issue?
The core problem lies in how jQuery binds events by default. When you use code like $('.like-button').click(...), jQuery only attaches that click event to elements that exist in the DOM when the page first loads.
- For the AJAX-generated buttons: When you replace the original button with new HTML from your AJAX response, that new button wasn't around when the initial event binding ran—so it has no click event attached, hence no reaction when clicked.
- For the repeated click requiring a refresh: After the first AJAX call, the original button element gets modified or replaced. The event binding was tied to that old element, so the updated button doesn't recognize the click until you reload and re-bind the event.
The fix: Use Event Delegation
Instead of binding events directly to the button elements, you'll bind the event to a persistent parent element (like document, or a container div that wraps all your like buttons). This way, the event "bubbles up" to the parent, which checks if the clicked element matches your selector (.like-button) and runs your code—regardless of whether the button was there on page load or added later via AJAX.
Here's how to adjust your code:
Original (broken) binding:
$('.like-button').click(function() { // Your AJAX logic here $.ajax({ url: 'your-like-handler.php', method: 'POST', data: { postId: $(this).data('post-id') }, success: function(response) { $(this).replaceWith(response); } }); });
Fixed code with event delegation:
// Bind to a stable parent (document works, but a closer container is more efficient) $(document).on('click', '.like-button', function() { var $targetButton = $(this); // Store the button reference for the AJAX callback $.ajax({ url: 'your-like-handler.php', method: 'POST', data: { postId: $targetButton.data('post-id') }, success: function(response) { // Replace the button with the updated HTML from your PHP response $targetButton.replaceWith(response); // No need to re-bind events here—delegation handles the new button automatically! } }); });
Do you need to reload jQuery?
Absolutely not! You don't have to reload jQuery at all. The only change needed is switching from direct event binding to event delegation. This eliminates the need to re-bind events every time you update the button via AJAX.
Quick extra tips:
- Ensure your PHP response returns the full, updated button HTML (including correct classes, counter values, and
data-post-idattributes). - Store the button reference in a variable like
$targetButtonbefore the AJAX call—this avoids context issues wherethisdoesn't point to the button inside thesuccesscallback.
内容的提问来源于stack exchange,提问作者Stephen Becker

