更新:使用 Bootstrap Switch 时,您可以使用以下两个功能之一:
$(this).bootstrapSwitch("toggleDisabled"); // toggles whether `this` is disabled
$(this).bootstrapSwitch("disabled",true); // just disables the `this` element
因此,在您的onSwitchChange处理程序中,您可以使用以下bootstrapSwitch("disabled", true)方法:
onSwitchChange:function(event, state) {
$(this).bootstrapSwitch('disabled', true);
}
“切换”没有真正的意义,因为它在一个处理程序中,当它改变时——当它被禁用时,它不应该再次改变。
上一个答案 - 对于那些想要使用 jQuery 禁用元素的人
如果要将表单元素设置为disabled,则需要声明其disabled 属性。
是否应该将其设置为true、刚刚声明或设置为存在争议disabled。
个人(也是最有利/兼容的)是设置disabled=disabled.
要使用 jQuery 设置元素属性,可以使用attr()函数(第一个参数是属性,第二个参数是值):
onSwitchChange:function(event, state) {
$(this).attr('disabled', 'disabled'); // set the element's disabled attribute
}
注意:由于您禁用了该复选框 - 这意味着它的值不会以form.
如果您需要将值与表单一起发布,请使用该readonly属性并将其设置为readonly:
onSwitchChange:function(event, state) {
$(this).attr('readonly', 'readonly'); //checkbox is readonly, but still POSTed
}
disabled这是一个很好的答案,解释了和之间的区别readonly:https ://stackoverflow.com/a/7357314/6240567
编辑:上面的代码只禁用/只读checkbox本身。为了禁用容器或其中的其他元素,您需要使用.closest()选择器。
关于选择器的重要提示,以及您需要哪些:
div匹配元素类型- 在这种情况下,它选择div元素。
.some-class匹配类 - 在这种情况下,任何以“ some-class”作为类的元素
#someId匹配元素id- 在这种情况下,它选择带有id“ someId”的元素
话虽如此,然后您可以选择closest要禁用的元素(或它的容器)
例如:
// set the checkbox's closest element with "bootstrapSwitch" class, to disabled
$(this).closest('.bootstrapSwitch').attr('disabled', 'disabled');
希望这可以帮助!:)