已禁用按钮仍会侦听单击事件 [英] Disabled button still listens to click event
问题描述
我在表单中遇到问题,我会进行一些jquery验证。如果未填写特定输入字段,则应通过添加禁用属性来禁用前进按钮:
I have a problem in a form where I do some jquery validations. If a specific input field is not filled out, it should disable a "step forward" button by adding a disabled attribute:
if errors
$('.btn-move-forward').attr("disabled", true)
有效,但我在该按钮上也有一个点击事件:
(coffeescript)
that works but I also have a click event on that button: (coffeescript)
$('.btn-move-forward').click ->
$('#step2, #step3').toggle()
我希望 .btn-move-forward
在按钮被禁用时不会触发点击事件但它确实!!
I expect .btn-move-forward
to not fire the click event when the button is disabled but it does!!
首先:我不明白为什么,因为每个浏览器规范都定义了这不应该发生。无论如何,我试图通过以下方式绕过它:
First: I don't understand why because every browser spec defines that this should not happen. Anyways, I tried to bypass it by doing the following stuff:
$('.btn-move-forward').click ->
if !$(this).is(:disabled)
$('#step2, #step3').toggle()
或者
$('.btn-move-forward').click ->
if $(this).prop("disabled", false)
$('#step2, #step3').toggle()
或组合这样的事件监听器:
or combining the event listeners like this:
$('.btn-move-forward').on 'click', '.btn-move-forward:enabled', ->
$('#step2, #step3').toggle()
不,全部这将无法正常工作。该按钮仍然可以作为前进按钮。
No, all of this won't work properly. The button still behaves as a move-forward button.
我想要的是按钮不听 onclick
如果它已被禁用。
All I want is the button not listening to onclick
if it is disabled.
推荐答案
已禁用
属性仅适用于表单元素。这意味着除非 .btn-move-forward
元素是< button>
或< input type =button>
然后已禁用
属性将无效。
The disabled
property only applies to form elements. This means that unless the .btn-move-forward
element is a <button>
or <input type="button">
then the disabled
attribute will have no effect.
你可以在这里看到一个使用按钮的工作示例
:
You can see a working example using a button
here:
$('.btn-move-forward').prop("disabled", true).click(function() {
console.log('Moving forward...');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="btn-move-forward">Move forward</button>
这篇关于已禁用按钮仍会侦听单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!