使用bootstrap switch插件,有时需要校验参数什么的,不通过按钮状态需要返回原来的状态,但是需要避免再次触发,请看代码: (注意:bootstrap switch插件版本一定引入要新版的,旧版有很多bug) <link rel="stylesheet" href="css/bootstrap.min.css" /> <link href="https://cdn.bootcss.com/bootstrap-switch/4.0.0-alpha.1/css/bootstrap-switch.min.css" rel="stylesheet">
<input style="margin-right: 5px;" name="status" type="checkbox" checked> <script src="https://cdn.bootcss.com/bootstrap-switch/4.0.0-alpha.1/js/bootstrap-switch.min.js"></script>
$('[name="status"]').bootstrapSwitch({ //初始化按钮
onText:"开启",
offText:"关闭",
onColor:"success",
offColor:"info",
size:"small",
onSwitchChange:function(event,state){
if(校验方法()){
//事件拦截,不改变状态 注意:第三个参数true代表不继续触发switch改变事件,不然会死循环的!!
$(this).bootstrapSwitch("toggleState",!state,true);
}
}
});