bootstrapSwitch 不要在点击时切换开关

bootstrapSwitch Don't toggle switch on click

我有一个 bootstrap 开关,但我不希望它每次都切换。我想检查条件是否为真,然后才切换开关。我怎样才能做到这一点?这是我目前所拥有的:

$("[name='relVal']").bootstrapSwitch({
    onSwitchChange: function(event, state) {
       if (condition_is_met) {
          $("[name='relVal']").bootstrapSwitch('state', true);
       }
    }
})

From the docs:

onSwitchChange

Callback function to execute on switch state change. If false is returned, the status will be reverted, otherwise nothing changes

所以您需要做的就是 return true/false 切换是否实际发生。

$("[name='relVal']").bootstrapSwitch({
    onSwitchChange: function(event, state) {
        if (condition_is_met) {
            return true;
        }

        return false;

        // Or as a one-liner
        // return condition_is_met;
    }
});