禁用/启用按钮和链接的最简单方法是什么(jQuery + Bootstrap)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16777003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:44:42  来源:igfitidea点击:

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

jqueryhtmlcsstwitter-bootstrap

提问by biofractal

Sometimes I use anchors styled as buttons and sometimes I just use buttons. I want to disable specific clicky-things so that:

有时我使用样式为按钮的锚点,有时我只使用按钮。我想禁用特定的clicky-things,以便:

  • They look disabled
  • They stop being clicked
  • 他们看起来残疾
  • 他们不再被点击

How can I do this?

我怎样才能做到这一点?

回答by James Donnelly

Buttons

纽扣

Buttons are simple to disable as disabledis a button property which is handled by the browser:

按钮很容易禁用,因为disabled它是由浏览器处理的按钮属性:

<input type="submit" class="btn" value="My Input Submit" disabled/>
<input type="button" class="btn" value="My Input Button" disabled/>
<button class="btn" disabled>My Button</button>

To disable these with a custom jQuery function, you'd simply make use of fn.extend():

要使用自定义 jQuery 函数禁用这些功能,您只需使用fn.extend()

// Disable function
jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            this.disabled = state;
        });
    }
});

// Disabled with:
$('input[type="submit"], input[type="button"], button').disable(true);

// Enabled with:
$('input[type="submit"], input[type="button"], button').disable(false);

JSFiddle disabled button and input demo.

JSFiddle 禁用按钮和输入演示

Otherwise you'd make use of jQuery's prop()method:

否则你会使用 jQuery 的prop()方法:

$('button').prop('disabled', true);
$('button').prop('disabled', false);


Anchor Tags

锚定标签

It's worth noting that disabledisn't a valid propertyfor anchor tags. For this reason, Bootstrap uses the following styling on its .btnelements:

值得注意的是,这disabled不是锚标记的有效属性。出于这个原因,Bootstrap 在其.btn元素上使用以下样式:

.btn.disabled, .btn[disabled] {
    cursor: default;
    background-image: none;
    opacity: 0.65;
    filter: alpha(opacity=65);
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    color: #333;
    background-color: #E6E6E6;
}

Note how the [disabled]property is targeted as well as a .disabledclass. The .disabledclass is what is needed to make an anchor tag appear disabled.

请注意该[disabled]属性是如何定位的以及如何定位的.disabled。该.disabled班是什么是需要做一个锚定标记显示为禁用。

<a href="http://example.com" class="btn">My Link</a>

Of course, this will not prevent links from functioning when clicked. The above link will take us to http://example.com. To prevent this, we can add in a simple piece of jQuery code to target anchor tags with the disabledclass to call event.preventDefault():

当然,这不会阻止链接在单击时起作用。上面的链接会将我们带到http://example.com。为了防止这种情况,我们可以添加一段简单的 jQuery 代码来使用disabled要调用的类来定位锚标记event.preventDefault()

$('body').on('click', 'a.disabled', function(event) {
    event.preventDefault();
});

We can toggle the disabledclass by using toggleClass():

我们可以disabled使用toggleClass()以下方法切换类:

jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            var $this = $(this);
            $this.toggleClass('disabled', state);
        });
    }
});

// Disabled with:
$('a').disable(true);

// Enabled with:
$('a').disable(false);

JSFiddle disabled link demo.

JSFiddle 禁用链接演示



Combined

组合

We can then extend the previous disable function made above to check the type of element we're attempting to disable using is(). This way we can toggleClass()if it isn't an inputor buttonelement, or toggle the disabledproperty if it is:

然后我们可以扩展上面的禁用函数来检查我们尝试禁用的元素类型is()。这样我们就可以toggleClass()在它不是inputorbutton元素时,或者在disabled它是时切换属性:

// Extended disable function
jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            var $this = $(this);
            if($this.is('input, button, textarea, select'))
              this.disabled = state;
            else
              $this.toggleClass('disabled', state);
        });
    }
});

// Disabled on all:
$('input, button, a').disable(true);

// Enabled on all:
$('input, button, a').disable(false);

Full combined JSFiddle demo.

完全结合的 JSFiddle 演示

It's worth further noting that the above function will also work on all input types.

值得注意的是,上述函数也适用于所有输入类型。

回答by oikonomopo

I can't think a simpler/easier way! ;-)

我想不出更简单/更简单的方法!;-)



Using Anchor tags (Links) :

使用锚标签(链接):

<a href="#delete-modal" class="btn btn-danger" id="delete">Delete</a>


To enable the Anchor tag:

要启用锚标记:

 $('#delete').removeClass('disabled');
 $('#delete').attr("data-toggle", "modal");

enter image description here

在此处输入图片说明



To disable the Anchor tag:

要禁用锚标记:

 $('#delete').addClass('disabled');
 $('#delete').removeAttr('data-toggle');

enter image description here

在此处输入图片说明

回答by Sohail xIN3N

Suppose you have text field and submit button,

假设您有文本字段和提交按钮,

<input type="text" id="text-field" />
<input type="submit" class="btn" value="Submit"/>

Disabling:

禁用:

To disable any button, for example, submit button you just need to add disabledattribute as,

要禁用任何按钮,例如,提交按钮,您只需要添加禁用属性,

$('input[type="submit"]').attr('disabled','disabled');

After executing above line, your submit button html tag would look like this:

执行以上行后,您的提交按钮 html 标签将如下所示:

<input type="submit" class="btn" value="Submit" disabled/>

Notice the 'disabled' attribute has added.

请注意,'disabled' 属性已添加

Enabling:

启用:

For enabling button, such as when you have some text in text field. You will need to remove the disableattribute to enable button as,

用于启用按钮,例如当您在文本字段中有一些文本时。您将需要删除禁用属性以启用按钮,

 if ($('#text-field').val() != '') {
     $('input[type="submit"]').removeAttr('disabled');
 }

Now the above code will remove the 'disabled' attribute.

现在上面的代码将删除 'disabled' 属性。

回答by Ricardo Zea

I know I'm late to the party, but to specifically answer the two questions:

我知道我参加聚会迟到了,但要专门回答两个问题:

"I just want to disable specific clicky-things so that:

“我只想禁用特定的可点击事物,以便:

  • They stop clicking
  • They look disabled
  • 他们停止点击
  • 他们看起来残疾

How hard can this be?"

这能有多难?”

They stop clicking

他们停止点击

1.  For buttons like <button>or <input type="button">you add the attribute: disabled.

1.对于像<button>或这样的按钮<input type="button">添加属性:disabled

<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>

2.  For links, ANY link... actually, any HTML element, you can use CSS3 pointer events.

2. 对于链接,任何链接……实际上,任何 HTML 元素,您都可以使用 CSS3指针事件

.selector { pointer-events:none; }

Browser support for pointer events is awesome by today's state of the art (5/12/14). But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events. So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers.

以当今最先进的技术 (5/12/14) 来看,浏览器对指针事件的支持非常棒。但是我们通常必须在 IE 领域支持旧版浏览器,因此 IE10 及以下不支持指针事件:http: //caniuse.com/pointer-events。因此,使用其他人在这里提到的 JavaScript 解决方案之一可能是旧浏览器的选择。

More info about pointer events:

有关指针事件的更多信息:

They look disabled

他们看起来残疾

Obviously this a CSS answer, so:

显然这是一个 CSS 答案,所以:

1.  For buttons like <button>or <input type="button">use the [attribute]selector:

1.对于像<button><input type="button">使用[attribute]选择器这样的按钮:

button[disabled] { ... }

input[type=button][disabled] { ... }

--

——

Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/

这是我在这里提到的内容的基本演示:http: //jsfiddle.net/bXm5B/4/

Hope this helps.

希望这可以帮助。

回答by Graham Laight

If, like me, you just want to disable a button, don't miss the simple answer subtly hidden in this long thread:

如果像我一样,您只想禁用一个按钮,请不要错过这个长线程中巧妙隐藏的简单答案:

 $("#button").prop('disabled', true);

回答by biofractal

@James Donnelly has supplied a comprehensive answer that relies on extending jQuery with a new function. That is a great idea, so I am going to adapt his code so it works the way I need it to.

@James Donnelly 提供了一个全面的答案,该答案依赖于使用新函数扩展 jQuery。这是个好主意,所以我将调整他的代码,使其按我需要的方式工作。

Extending jQuery

扩展jQuery

$.fn.disable=-> setState $(@), true
$.fn.enable =-> setState $(@), false
$.fn.isDisabled =-> $(@).hasClass 'disabled'

setState=($el, state) ->
    $el.each ->
        $(@).prop('disabled', state) if $(@).is 'button, input'
        if state then $(@).addClass('disabled') else $(@).removeClass('disabled')

    $('body').on('click', 'a.disabled', -> false)

Usage

用法

$('.btn-stateful').disable()
$('#my-anchor').enable()

The code will process a single element or a list of elements.

该代码将处理单个元素或元素列表。

Buttons and Inputs support the disabledproperty and, if set to true, they will look disabled (thanks to bootstrap) and will not fire when clicked.

按钮和输入支持该disabled属性,如果设置为true,它们将看起来被禁用(感谢引导程序)并且在单击时不会触发。

Anchors don't support the disabled property so instead we are going to rely on the .disabledclass to make them look disabled (thanks to bootstrap again) and hook up a default click event that prevents the click by returning false (no need for preventDefaultsee here).

锚不支持禁用的属性,因此,而不是我们要依靠.disabled类,使它们看起来禁用(感谢再次引导)和挂钩默认点击事件,可防止通过点击返回false(无需preventDefault这里) .

Note: You do not need to unhook this event when re-enabling anchors. Simply removing the .disabledclass does the trick.

注意:重新启用锚点时,您不需要取消挂接此事件。简单地删除.disabled类就可以了。

Of course, this does not help if you have attached a custom click handler to the link, something that is very common when using bootstrap and jQuery. So to deal with this we are going tro use the isDisabled()extension to test for the .disabledclass, like this:

当然,如果您将自定义单击处理程序附加到链接,这将无济于事,这在使用引导程序和 jQuery 时非常常见。因此,为了解决这个问题,我们将使用isDisabled()扩展来测试.disabled该类,如下所示:

$('#my-anchor').click -> 
    return false if $(@).isDisabled()
    # do something useful

I hope that helps simplify things a bit.

我希望这有助于简化事情。

回答by Henrik Heimbuerger

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.

请注意,如果您使用 Bootstrap 的 JS 按钮和“加载”状态,则会出现一个奇怪的问题。我不知道为什么会发生这种情况,但这是解决它的方法。

Say you have a button and you set it to the loading state:

假设您有一个按钮并将其设置为加载状态:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:

现在你想把它从加载状态中取出,但也要禁用它(例如,按钮是一个保存按钮,加载状态表示正在进行的验证和验证失败)。这看起来像合理的 Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. Apparently, button()performs some delayed task. So you'll also have to postpone your disabling:

不幸的是,这将重置按钮,但不会禁用它。显然,button()执行一些延迟的任务。因此,您还必须推迟禁用:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot.

有点烦人,但这是我经常使用的模式。

回答by Brandon Johnson

Great answer and contributions from all! I had to extend this function slightly to include disabling of select elements:

很好的答案和所有人的贡献!我必须稍微扩展此功能以包括禁用选择元素:

jQuery.fn.extend({
disable: function (state) {
    return this.each(function () {
        var $this = jQuery(this);
        if ($this.is('input, button'))
            this.disabled = state;
        else if ($this.is('select') && state)
            $this.attr('disabled', 'disabled');
        else if ($this.is('select') && !state)
            $this.removeAttr('disabled');
        else
            $this.toggleClass('disabled', state);
    });
}});

Seems to be working for me. Thanks all!

似乎对我有用。谢谢大家!

回答by El Bayames

For that kind of behavior I always use the jQueryUI buttonwidget, I use it for links and buttons.

对于这种行为,我总是使用 jQueryUIbutton小部件,我将它用于链接和按钮。

Define the tag within HTML:

在 HTML 中定义标签:

<button id="sampleButton">Sample Button</button>
<a id="linkButton" href="yourHttpReferenceHere">Link Button</a>

Use jQuery to initialize the buttons:

使用 jQuery 初始化按钮:

$("#sampleButton").button();
$("#linkButton").button();

Use the buttonwidget methods to disable/enable them:

使用button小部件方法禁用/启用它们:

$("#sampleButton").button("enable"); //enable the button
$("#linkButton").button("disable"); //disable the button

That will take care of the button and cursor behavior, but if you need to get deeper and change the button style when disabled then overwrite the following CSS classes within your page CSS style file.

这将处理按钮和光标的行为,但如果您需要更深入地了解并在禁用时更改按钮样式,请覆盖页面 CSS 样式文件中的以下 CSS 类。

.ui-state-disabled,
.ui-widget-content .ui-state-disabled,
.ui-widget-header .ui-state-disabled {
      background-color:aqua;
      color:black;
 }

But remember: those CSS classes (if changed) will change the style for other widgets too.

但请记住:这些 CSS 类(如果更改)也会更改其他小部件的样式。

回答by Raptor

The following has worked for me very well:

以下对我来说非常有效:

$("#button").attr('disabled', 'disabled');