jQuery 单击复选框时更改div的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10889408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change background color of div when checkbox is clicked
提问by DobotJr
I have a form with several checkboxes, like this:
我有一个带有多个复选框的表单,如下所示:
<div><input type='checkbox' name='groupid' value='1'>1</div>
<div><input type='checkbox' name='groupid' value='2'>2</div>
<div><input type='checkbox' name='groupid' value='3'>3</div>
What I'm trying to do is when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?
我想要做的是当复选框被选中时,更改 div 的背景颜色,当它取消选中时,删除背景颜色。我如何使用 jquery 做到这一点?
Thanks
谢谢
回答by ahren
jQuery:
jQuery:
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")){
$(this).parent().addClass("redBackground");
}else{
$(this).parent().removeClass("redBackground");
}
});
CSS:
CSS:
.redBackground{
background-color: red;
}
I'd recommend using Add/Remove class, as opposed to changing the CSS of the parent div
directly.
我建议使用 Add/Remove 类,而不是直接更改父级的 CSS div
。
回答by VisioN
One solution with direct CSS attribute changing:
直接更改 CSS 属性的一种解决方案:
$(":checkbox").on("change", function() {
var that = this;
$(this).parent().css("background-color", function() {
return that.checked ? "#ff0000" : "";
});
});?
DEMO:http://jsfiddle.net/YQD7c/
演示:http : //jsfiddle.net/YQD7c/
Another solution using toggleClass
:
使用的另一种解决方案toggleClass
:
$(":checkbox").on("change", function() {
$(this).parent().toggleClass("checked", this.checked);
});?
Where you define class checked
in CSS as follows:
checked
在 CSS 中定义类的位置如下:
.checked {
background-color: #ff0000;
}?
回答by duggy
I am aware that this is an old thread, but I came searching and this answer got me most of the way. (needed some tweaking for WordPress) So if someone else lands on this same page that is using WordPress, give this a shot, worked great for me.
我知道这是一个旧线程,但我是来搜索的,这个答案让我大获全胜。(需要对 WordPress 进行一些调整)因此,如果其他人在使用 WordPress 的同一页面上登陆,请试一试,对我来说效果很好。
The Script
剧本
jQuery("input[type='checkbox']").change(function(){
if(jQuery(this).is(":checked")){
jQuery(this).parent().addClass("greenBackground");
}
else{
jQuery(this).parent().removeClass("greenBackground");
} });
The CSS
CSS
.greenBackground{
background-color: #06530e;
color: #ffffff;}