bootstrap-switch,切换触发事件及动态切换以及readonly属性设置

注意不能再<input type="checkbox" name="switch">中添加readonly或者disabled属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <link href="https://cdn.bootcss.com/bootstrap-switch/3.3.4/css/bootstrap3/bootstrap-switch.css" rel="stylesheet">
    <style>
        .center{
            text-align: center;
            margin-top: 100px;
        }
        #state{
            font-size: 20px;
            color: black;
            font-family: "Adobe 黑体 Std R";
            font-weight: bold;
        }
        .btn{
            width: 60px;
        }
    </style>
</head>
<body>
    <div class="center">
        <input type="checkbox" name="switch">
        <p id="state"></p><br>
        <button type="button" class="btn btn-primary" id="on">on</button>
        <button type="button" class="btn btn-warning" id="off">off</button>
    </div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-switch/3.3.4/js/bootstrap-switch.js"></script>
<script>
 
    $("input[name='switch']").bootstrapSwitch({
        onText: "开启",
        offText: "关闭",
        onSwitchChange: function (event, state) {
            //监听switch change事件,可以根据状态把相应的业务逻辑代码写在这里
            if (state == true) {
                $("#state").html('switch turn no');
                $(this).val("0");
            } else {
                $("#state").html('switch turn off');
                $(this).val("1");
            }
        }
    })
    //两个按钮点击动态切换bootsrap开关状态
    $("#on").click(function(e){
        $("input[name='switch']").bootstrapSwitch("state",true);
    })
 
    $("#off").click(function(e){
        $("input[name='switch']").bootstrapSwitch("state",false);
    })
</script>
</html>

如果有这样一个需求。根据某个值,去设置switch按钮的state后,并且想让其不可再点击滑动,可这样写。

// 每次执行js前先初始化readonly位false。如果没有这句,执行下面某个if语句后,另外一个if语句的readonly设置就无效了
$("#status").bootstrapSwitch("readonly", false);

if(data.data.status=='0'){
         
            $("#status").bootstrapSwitch("state", true);
            $("#status").bootstrapSwitch("readonly", true);
 }

 if(data.data.status=='1'){
            $("#status").bootstrapSwitch("state", false);
            $("#status").bootstrapSwitch("readonly", true);
  }

 

转载于https://www.cnblogs.com/guofx/p/11198292.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值