如何使用原生JS触发禁用按钮元素的点击事件?
Great question! The core issue here is that disabled HTML form elements don't fire native click events—browsers intentionally block this behavior to align with standard form interaction rules. But we can work around this using native JS with event delegation, no jQuery required.
Why Your Current Code Fails
When you bind onclick directly to a disabled button, the browser ignores any click actions on it entirely. That’s exactly why your sendData function never runs when the button is disabled.
The Native JS Fix: Event Delegation
Instead of attaching the click event directly to the disabled button, we’ll bind it to a parent element (like your existing this.$form). Parent elements still capture click events even when their child elements are disabled, so we can check if the click originated from our disabled button and trigger our logic manually.
Here’s how to update your bindEvents function:
bindEvents: function() { var that = this; // Replace direct button click binding with event delegation on the form this.$form.addEventListener('click', function(e) { // Check if the click target is our "show" button (or any child element inside it) const clickedButton = e.target.closest('[your-show-button-selector]'); // If your button has an ID, use that for better specificity: e.target.closest('#show-btn') if (clickedButton === that.show) { e.preventDefault(); // Keep your existing preventDefault logic that.sendData.call(that, e); // Ensure `this` in sendData points to your component } }); // Keep your existing input change handler this.$form.change(function(){ that.updateDatesInputs(this); }); }
Key Details to Keep in Mind:
closest()for Reliable Targeting: Usinge.target.closest()ensures we catch clicks even if the button contains child elements (like icons or text spans). If your button has no children, you can simplify the check toe.target === that.show.- Preserve Context with
call():that.sendData.call(that, e)makes surethisinside yoursendDatafunction still refers to your component instance, just like your originalbind(this)did. - No Changes to
sendData: Your existingsendDatalogic works exactly as is—you don’t need to modify the check forthis.show.disabledor the alert behavior.
Alternative: Bind to a Closer Container (or Document)
If you don’t want to use the form as the parent, you can bind the event to a closer container element, or even document (though closer is better for performance):
document.addEventListener('click', function(e) { if (e.target.closest('#show-btn') === that.show) { e.preventDefault(); that.sendData.call(that, e); } });
This approach lets you trigger your disabled button’s click logic purely with native JavaScript, no jQuery dependencies needed.
内容的提问来源于stack exchange,提问作者Imnotapotato

