将onclick事件绑定到bootstrap-switch

时间:2016-11-02 09:50:27

标签: jquery bootstrap-switch

我正在构建一个应该根据用户做出的 bootstrap-switch 选项隐藏和显示内容的表单。 onclick =“documentFilter事件在正常的复选框上工作;但是,当我初始化bootstrap-switch时,代码无法正常工作。任何想法我都缺少了?谢谢!

<!--DEPENDENCIES-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.min.js"></script>

<!--HTML-->
<body>
    
    <div class="container">
        <label>
            <input type="checkbox" name="my-checkbox" onclick="documentFilter(this, '#hideableDiv')"> Some caption
        </label>

        <div id="hideableDiv" class="hiddenByDefault">Some hidable content
        </div>
    </div>

</body>

<!--PAGE-SPECIFIC SCRIPT-->

<script type="text/javascript">

//Initialise BootstrapSwitch
$("[name='my-checkbox']").bootstrapSwitch();

//Unchecked on load
$(".hiddenByDefault").hide();

//document filter function
function documentFilter(trigger, target) {
    var $target = $(target);

    $(trigger).change(function () {
        $target.toggle(this.checked);
    });
}

</script>

1 个答案:

答案 0 :(得分:0)

如果您查看Bootstrap Switch library的文档,则会看到它具有onSwitchChange属性,您可以为其提供功能。切换开关时执行此功能。这样做的另一个好处就是无需使用过时且丑陋的on*事件属性。试试这个:

$("[name='my-checkbox']").bootstrapSwitch({
  onSwitchChange: function(e, state) {
    $('#hideableDiv').toggle(state);
  }
});
.hiddenByDefault { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap-theme.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap2/bootstrap-switch.min.css" />

<div class="container">
  <label>
    <input type="checkbox" name="my-checkbox" onclick="documentFilter(this, '#hideableDiv')">Some caption
  </label>

  <div id="hideableDiv" class="hiddenByDefault">Some hidable content
  </div>
</div>

相关问题