3

ユーザーが行ったブートストラップ スイッチの選択に従って、コンテンツを非表示および表示するフォームを作成しています。onclick="documentFilter イベントは通常のチェック ボックスで機能しますが、ブートストラップ スイッチを初期化した瞬間に、コードが意図したとおりに機能しません。何が欠けているか分かりますか?ありがとう!

<!--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>

4

1 に答える 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>

于 2016-11-02T09:56:17.907 に答える