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