簡體   English   中英

使用 jquery 函數引導程序切換 setState

[英]bootstrap switch setState using a jquery function

我正在嘗試使用兩個外部按鈕設置引導程序開關的狀態,這是代碼:

    <div>
        <input type="checkbox" name="switch" id="switch" value="1" data-on-text="ON" data-off-text="OFF" />
    </div>

    <div>
        <a id="set_on">ON</a>
        <a id="set_off">OFF</a>
    </div>

<script src="assets/jquery.min.js" type="text/javascript"></script>
<script src="assets/jquery-ui.min.js" type="text/javascript"></script>
<script src="assets/bootstrap.min.js" type="text/javascript"></script>
<script src="assets/bootstrap-switch.js"></script>
<script>
    $("#switch").bootstrapSwitch();
    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('setState', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('setState', false);
    });
</script>

單擊 ON 或 OFF 按鈕不會切換其狀態。 在瀏覽器的控制台上我讀到這個錯誤: TypeError: $(...).bootstrapSwitch is not a function

如果我嘗試以這種方式在函數外設置引導程序開關的狀態:

<script>
    $("#switch").bootstrapSwitch();
    $("#switch").bootstrapSwitch('setState', false);
</script>

開關正確切換到 ON 狀態。

請用以下代碼替換您的代碼:

    <script type="text/javascript">
    $( document ).ready(function() {
    $("#switch").bootstrapSwitch();

    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('state', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('state', false);
    });
    });
    </script>

嘗試將您的代碼包裝在$( document ).ready(function() {}); 以便在執行 jQuery 代碼之前加載所有 DOM 元素,如下所示:

<script>
$( document ).ready(function() {
    $("#switch").bootstrapSwitch();
    $("#switch").bootstrapSwitch('setState', false);
});
</script>

嘗試在您的完整腳本中像這樣使用它 -

<script>

 $( document ).ready(function() {
    $("#switch").bootstrapSwitch();
    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('setState', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('setState', false);
    });
});

</script>

你可以嘗試使用bootstrapSwitch() ,像這樣

 $("[name = 'status']").bootstrapSwitch();
 <input name = "status" type="checkbox">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM