在jQuery中切换禁用属性 [英] toggle disabled attribute in jquery

查看:93
本文介绍了在jQuery中切换禁用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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");
    }
});

这是最好的方法,还是像.toggle()这样的功能可以在禁用/启用之间进行切换?

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

推荐答案

您应使用.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; });

更新:ES2015

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

这篇关于在jQuery中切换禁用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆