简体   繁体   English

在event.preventDefault()之后重新启用按钮默认值

[英]Reenable button default after event.preventDefault()

I have a button like this in my html: 我的html中有一个像这样的按钮:

<button id="target" url="foo.com">Button Text</button>

Then I have a method to disable it: 然后我有一种禁用它的方法:

disableButton = function () {
    $("#target").click(function (event) {
        event.preventDefault();
    });
};

And I have a second method that I call after the disableButton method to reenable it: 我在disableButton方法之后调用了第二个方法来重新启用它:

enableButton = function() {
    $('#target').unbind('click');
    $('#target').bind('click');
    $("#target").trigger('click');
}; 

The problem is, when I call enableButton(), it doesn't trigger the button click. 问题是,当我调用enableButton()时,它不会触发按钮单击。 It only works if I call the enableButton() method and then manually click the button. 仅当我调用enableButton()方法,然后手动单击按钮时,它才有效。 Can anyone tell me how to make the enableButton() method trigger a button click when called? 谁能告诉我如何使enableButton()方法在调用时触发按钮单击?

Basically the workflow should be: 基本上,工作流程应为:

1) #target is clicked 1)单击#target

2) #target is disabled until we get a response from some outside source 2)#target被禁用,直到我们从某个外部源得到响应

3) Response is received 3)收到回应

4) Trigger a button click for #target without having to manually click the button again 4)触发#target的按钮单击,而无需再次手动单击按钮

You could try this. 你可以试试看。

disableButton = function () {
    $("#target").off("click");
};

enableButton = function() {
    $('#target').on("click", clickevent);
    $('#target').click();
};

where clickevent is a method which will be called when the button is clicked. 其中clickevent是单击按钮时将调用的方法。

PS. PS。 Correct your code (quotes in the code). 更正您的代码(代码中的引号)。 jQuery doesnt support unicode. jQuery不支持unicode。

You do not need to on/off events, click events will not invoke if you enable/disable button. 您不需要on/off事件,如果enable/disable按钮,则不会调用click事件。

Use .prop('disabled', callback) set one or more properties for every matched element. 使用.prop('disabled', callback) 为每个匹配的元素设置一个或多个属性。 [ Ref ] [ 参考 ]

Try this: 尝试这个:

 $('#enDis').on('click', function() { $('#myBtn').prop('disabled', function() { return !this.disabled; }); }); $('#myBtn').on('click', function() { alert('It is enabled!'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id='myBtn'>Main Button</button> <button id='enDis'>Enable/Disable</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM