[英]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.