gpt4 book ai didi

jquery - 关闭隐藏 div 时 Bootstrap 复选框切换

转载 作者:行者123 更新时间:2023-12-01 03:40:58 26 4
gpt4 key购买 nike

我的网站上有一个 Bootstrap 复选框开关。

http://www.bootstrap-switch.org/

当开关切换到关闭状态时,我想隐藏 div 类“name-number-form

但是我注意到,当开关打开和关闭时,选中的符号在关闭时不会消失。如果是这样的话我会这样做:

$(document).ready(function() {
$('.switch-on input[type=checkbox]').change(function(){
if($(this).is(':checked')){
$('.name-number-form').show();
} else {
$('.name-number-form').hide();
}
});
});

但是当我切换到关闭状态时,选中的内容不会消失,所以我尝试了以下方法:

$(document).ready(function() {
$('.switch-on').change(function(){
if($(this).is('.switch-on')){
$('.name-number-form').show();
} else {
$('.name-number-form').hide();
}
});
});

运气不好

我发出警报以查看该属性是否正常工作

$(document).ready(function() {
$('.switch-on').on('switch-change', function (e, data) {
alert('this is switch ' + $(this).attr('switch-id'));
var $el = $(data.el)
, value = data.value;
if(value){//this is true if the switch is on
$('.name-number-form').show();
}else{
$('.name-number-form').hide();
}
});
});

我为 name-number-form 创建了一个独特的属性,也称为 data-name-number-form

最佳答案

要捕获开关的更改,您需要为 switch-change 事件分配回调。例如,

http://jsfiddle.net/NuE7X/

$(document).ready(function() {
$('.switch-on').on('switch-change', function (e, data) {
var $el = $(data.el)
, value = data.value;
if(value){//this is true if the switch is on
$('.name-number-form').show();
}else{
$('.name-number-form').hide();
}
});
});

编辑 - 对评论的回复如果您想在 off 状态下启动并隐藏 div,您可以按如下方式修改 html,

<div class="make-switch switch-on">
<input type="checkbox">
</div>
<div class="name-number-form" style="display:none">this is name number form</div>

EDIT2 - 对评论的回复如果您有多个开关和关联的name-number-form,您可以使用 jQuery next 方法通过指定的选择器选择下一个同级。例如,

http://jsfiddle.net/V7gjM/

$(document).ready(function () {
$('.switch-on').on('switch-change', function (e, data) {

var $el = $(data.el),
value = data.value;
if (value) { //this is true if the switch is on
$(this).next('.name-number-form').show();
} else {
$(this).next('.name-number-form').hide();
}
});
});

关于jquery - 关闭隐藏 div 时 Bootstrap 复选框切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com