将onclick事件绑定到bootstrap-switch

3

我正在构建一个表单,根据用户使用的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个回答

3
如果您查看Bootstrap Switch库的源代码,您会发现它有一个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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接