在 jquery 中切换禁用属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11903293/
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 11:03:18  来源:igfitidea点击:

toggle disabled attribute in jquery

jquery

提问by Naigel

I've a checkbox that enable or disable a select element

我有一个启用或禁用选择元素的复选框

Actually I use this simple piece of code that works fine.

实际上我使用了这段简单的代码,效果很好。

$("#filtri").change(function(){
    if ($("#menuContinenti").attr("disabled")) {
        $("#menuContinenti").removeAttr("disabled");
    } else {
        $("#menuContinenti").attr("disabled", "disabled");
    }
});

Is this the best way or is there something like a .toggle()function to switch between disabled/enabled?

这是最好的方法还是有类似.toggle()功能可以在禁用/启用之间切换?

回答by Explosion Pills

You should use .propfor disabled:

你应该使用.prop残疾人:

$("#menuContinenti").prop('disabled', function () {
   return ! $(this).prop('disabled');
});

UPDATE: didn't realize the current property value is an argument to the function; this version is even cleaner:

更新:没有意识到当前属性值是函数的参数;这个版本更干净:

$("#menuContinenti").prop('disabled', function (_, val) { return ! val; });

UPDATE: ES2015

更新:ES2015

$("#menuContinenti").prop("disabled", (_, val) => !val);

回答by Moin Zaman

You can write your own plugin that does something like this.

你可以编写自己的插件来做这样的事情。

Add this after jQuery, in a script file preferably.

在 jQuery 之后添加它,最好在脚本文件中。

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

Then use it like this:

然后像这样使用它:

$('#my-select').toggleDisabled();

Courtesy: Toggle input disabled attribute using jQuery

礼貌:使用 jQuery 切换输入禁用属性

回答by Loken Makwana

you can check using $.is function like below

您可以使用 $.is 函数进行检查,如下所示

$("#filtri").change(function(){
    $("#menuContinenti").attr("disabled", ! $(this).is(':checked'));    
});