如何用jQuery在Ajax表单处理时或2秒内禁用点击事件
Hey there, I get it—dealing with duplicate click submissions can be super frustrating, especially when the usual tricks aren't landing. Let's break down how to solve this for your exact scenario.
First, let's fix a tiny but critical issue in your HTML: your form has an extra dot in the class attribute (class=".like-button-form"). That's going to break your jQuery selector because the dot is only used in the selector itself, not in the class name. Correct that first:
<form class="like-button-form" action="sdfs.php" method="POST"> <i class="fa-thumbs-up"></i> </form>
Now, for the click prevention. Since you don't want CSS-only hacks, don't want to permanently kill the click event with off(), and prop("disabled", true) isn't working (likely because you're targeting an <i> instead of a button element), let's use a request state flag to block duplicate clicks while the AJAX call is in progress.
Here's your revised JavaScript with the fix:
// Add a flag to track if a request is already running let isProcessing = false; $(".fa-thumbs-up").click(function( event ) { // Stop default action event.preventDefault(); // If a request is already in flight, exit immediately if (isProcessing) return; // Mark the request as started isProcessing = true; // Get form data (fixed the selector to target the correct form relative to the clicked icon) var $form = $(this).closest(".like-button-form"), data = $form.serialize(), url = $form.attr( "action" ); // Send the POST request var posting = $.post( url, data ); posting.done(function( data ) { response = JSON.parse(data); // Fixed the typo here (changed $(form) to $form) $form.children("input[name='likedornot']").attr("value", response.likedornot); }) // Always reset the flag when the request finishes—success OR failure .always(function() { isProcessing = false; }); });
Key Changes Explained:
- Request State Flag:
isProcessingacts as a simple gate—if it'strue, we bail out of the click handler right away, stopping duplicate submissions mid-request. - Selector Fixes: Used
$(this).closest(".like-button-form")to reliably target the form tied to the clicked icon, and fixed the typo where you used$(form)instead of the defined$formvariable. - Safe Reset: The
.always()method runs no matter if the request succeeds or fails, so we resetisProcessingevery time—this ensures the button works again after the request finishes (if you want to allow subsequent clicks later).
This approach is lightweight, doesn't rely on CSS, and doesn't permanently disable the click event. It just blocks clicks until the current request wraps up.
内容的提问来源于stack exchange,提问作者Josh Poor

