如何使用Bootstrap Toggle切换另一个Bootstrap Toggle

时间:2018-01-19 16:29:30

标签: jquery bootstrap-4

我遇到了bootstrap切换功能的问题。

这个想法是让一个复选框(bootstrap toggle)打开或关闭第二个复选框(bootstrap toggle)。可悲的是,它还没有在网页上工作。我注意到通过删除“data-toggle ='toggle'”函数可以正常工作,但即使对onclick()事件发出警报也没有响应。

function toggleOnByInput() {
    $('#toggle-trigger').prop('checked', true).change()
 }
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<script src="jquery-3.2.1.min.js"></script>
<input 
        type="checkbox" 
        id="week" 
        name="week" 
        data-toggle="toggle"                 
        data-onstyle="success" 
        data-offstyle="warning" 
        data-size="small"
        data-on="Yes" 
        data-off="No"
        onclick="toggleOnByInput()">

<input id="toggle-trigger" type="checkbox" data-toggle="toggle">

1 个答案:

答案 0 :(得分:2)

1.jQuery库需要先添加任何其他js库。

2.检查jQuery库文件路径是否正确。否则将不包含文件,您的代码将无效。

3.由于您正在使用bootstrap toogle,因此onclick将无效。您必须使用以下代码: -

$('body').on('click','.toggle-group:first',function(){
    $('.toggle-group:last').click();
});

我做了这些更改,代码开始正常工作: -

&#13;
&#13;
$('body').on('click','.toggle-group:first',function(){
  $('.toggle-group:last').click();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>

<input 
        type="checkbox" 
        id="week" 
        name="week" 
        data-toggle="toggle"                 
        data-onstyle="success" 
        data-offstyle="warning" 
        data-size="small"
        data-on="Yes" 
        data-off="No">

<input id="toggle-trigger" type="checkbox" data-toggle="toggle">
&#13;
&#13;
&#13;