2017-03-16 69 views
0

我正在使用this library来实现切换按钮。我有两个切换按钮。我的目的是在打开其中一个时,另一个应该关掉。引导切换 - 一个打开,另一个打开

由于库指示,我创建两个input元素:

<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-on" checked value="true"> 
<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-off"> 

而我的jQuery代码来处理它们:

$('.switch-on').change(function(){ 
    $(this).removeClass('switch-on'); 
    $(this).addClass('switch-off'); 
    $(this).bootstrapToggle(); 
}); 

$('.switch-off').click(function(){ 
    $(this).removeClass('switch-off'); 
    $(this).bootstrapToggle(); 
    $('.switch-on').click(); 
    $(this).addClass('switch-on'); 
}); 

我已经尝试了很多方法,包括更改类名,触发事件,但完全徒劳。当我检查元素时,类名甚至没有改变。为什么它不工作?

+0

一次检查此[链接](https://jsfiddle.net/knvnx2ks/1/) – rahulsm

回答

1

试试这个片断,

$("#toggle1").change(function() { 
 
    if ($(this).is(":checked")) { 
 
     $("#toggle2").bootstrapToggle('off'); 
 
    } 
 
}); 
 
$("#toggle2").change(function() { 
 
    if ($(this).is(":checked")) { 
 
     $("#toggle1").bootstrapToggle('off'); 
 
    } 
 
});
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script> 
 

 
<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-on toggle" checked value="true" id="toggle1"> 
 
<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-off toggle" id="toggle2">

+0

非常感谢你。它非常出色! – necroface