简体   繁体   English

使用jquery在check操作上切换复选框的父类

[英]Toggle parent class of checkbox on check action using jquery

I am trying to make a form with multiple checkboxes. 我正在尝试制作一个包含多个复选框的表单。 I want to highlight the checkboxes with their content to indicate to the user of the selection 我想突出显示其内容的复选框,以向用户指示选择
I am using the following layout for my form 我正在为我的表单使用以下布局

HTML HTML

<form>
<div class=labl>
<input type=checkbox id='alpha' />
<label for='alpha'>Checkbox1</label>
</div>

CSS CSS

.labl{

height:50px;
}
.labl:hover{
background:#ccc;
}
.chked {
background: #4285f4;
height:50px;
}

jQuery jQuery的

<script>

$("input[type=checkbox]").change(function() {
    $(this).parent().toggleClass("chked");
});

</script>


Now when alpha is checked it should change the class of div from labl to chked 现在当检查alpha时,它应该将div的类从labl更改为chked
but it is not 但事实并非如此

You need a DOM ready handler like this $(function(){...}); 你需要一个DOM就绪处理程序,比如$(function(){...});

$(function () {
    $("input[type=checkbox]").change(function () {
        $(this).parent().toggleClass("chked");
    });
});

Documentation 文档

Update 更新

It appears that the checkbox is dynamically added to the DOM so you must use event delegation like this 看来复选框是动态添加到DOM的,所以你必须使用这样的事件委托

    $(document).on("change","input[type=checkbox]",function () {
        $(this).parent().toggleClass("chked");
    });

You can pass both the class names to the toggleClass() method, so that only one of the will be applied at a time 您可以将类名传递给toggleClass()方法,以便一次只应用其中一个

jQuery(function(){
    $("input[type=checkbox]").change(function() {
        $(this).parent().toggleClass("labl chked");
    });
})

Demo: Fiddle 演示: 小提琴

just change your script to 只需将脚本更改为

$("input[type=checkbox]").change(function() {
    $(this).parents('.labl').toggleClass("chked");
}); 

And your HTML to 和你的HTML

<form>
<div class='labl'>
    <input type='checkbox' id='alpha'></input>
<label for='alpha'>Checkbox1</label>
</div>

Here is the updated fiddle 这是更新的小提琴

http://jsfiddle.net/k242J/ http://jsfiddle.net/k242J/

toggleClass functionality is to check the class, if not there it will add, else remove class thats it. toggleClass功能是检查类,如果没有它会添加,否则删除它就是这样的类。 its not to change from one class to another. 它不会从一个班级改为另一个班级。

css CSS

.chked {
    background: #4285f4;
}

js JS

$("input[type=checkbox]").change(function() {
     $(this).parent().toggleClass("chked");
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM