Bootstrap Toggle - 一个打开,另一个关闭

nec*_*ace 0 html javascript jquery toggle twitter-bootstrap-3

我正在使用这个库来实现切换按钮。我有两个切换按钮。我的目的是当打开其中一个时,另一个应该关闭。

按照库的指示,我创建了两个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">
Run Code Online (Sandbox Code Playgroud)

我的 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');
});
Run Code Online (Sandbox Code Playgroud)

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

Rah*_*hul 5

试试这个片段,

$("#toggle1").change(function() {
  if ($(this).is(":checked")) {
      $("#toggle2").bootstrapToggle('off');
  }
});
$("#toggle2").change(function() {
  if ($(this).is(":checked")) {
      $("#toggle1").bootstrapToggle('off');
  }
});
Run Code Online (Sandbox Code Playgroud)
<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">
Run Code Online (Sandbox Code Playgroud)