繁体   English   中英

具有多个相同输入的引导程序切换不起作用

[英]bootstrap toggle with multiple same input not working

具有多个相同输入的Bootstrap切换不起作用,除非不按第一个输入。并且仍然没有选中/取消选中所有它们。

我做了一个小例子

如果我按一个,则需要使所有其他状态都相同。

$(document).ready(function(){
  $('.testClass').on('change', function() {
    if($(this).prop('checked')) {
      $('.testClass').each(function(key, val) {
        $(val).bootstrapToggle('on');
      });
    } else {
      $('.testClass').each(function(key, val) {
        $(val).bootstrapToggle('off');
      });
    }
  })
});

任何建议如何实现这一目标?

@ digital-pollution击败了我,但我认为我找到了一个更好的解决方案。 它基本上从一开始on('change')删除on('change')事件,并在最后将其添加回去。

 var toggleButtons = function toggleButtons() { $('.testClass').off('change'); if($(this).prop('checked')) { $('.testClass').not($(this)).each(function(key, val) { $(val).bootstrapToggle('on'); }); } else { $('.testClass').not($(this)).each(function(key, val) { $(val).bootstrapToggle('off'); }); } $('.testClass').on('change', toggleButtons); } $(document).ready(function(){ $('.testClass').on('change', toggleButtons); }); 
 <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <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> <input type="checkbox" class="testClass" data-toggle="toggle" data-on="test" data-off="NOT" > <input type="checkbox" class="testClass" data-toggle="toggle" data-on="test" data-off="NOT" > <input type="checkbox" class="testClass" data-toggle="toggle" data-on="test" data-off="NOT" > 

看起来该代码正在引起无限循环,我对插件不熟悉,但是可以解决。 如果我了解目标,则当更改一个目标时,您希望将所有开关都设置为相同状态。

$(document).ready(function(){
  $('.toggle-group').on('click', function(e) {
    // wait for the plugin to update the actual checkbox
    setTimeout(function(){
        // check if the checkbox is checked or not  
        var state = ( $(e.currentTarget).prev('input')[0].checked ) ?
        'on' : 'off';

      // update all the bootstrapToggle checkbox instances with the new 
      // state
      $('.testClass').each(function(key, val) {
        $(val).bootstrapToggle(state);
      });

    }, 50);
  });
});

我认为正在发生的事是示例代码中的“ change”事件不断循环触发。 这个答案远非完美的解决方案,而是突出了问题所在。 setTimeout允许插件在测试前更新复选框,因为它看起来不像bootstrapToggle接受任何回调。

只需从代码中删除$('.testClass').each(function(key, val) {

  $(document).ready(function(){
    $('.testClass').on('change', function() {
      if($(this).prop('checked')) {
          $(this).bootstrapToggle('on');
      } else {
          $(this).bootstrapToggle('off');
      }
    })
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM