javascript 使用 Jquery 检查时更改复选框的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11423438/
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 a checkbox when checked with Jquery
提问by Vikram
I'm trying to change the background color of a div with a checkbox in it. I've made this http://jsfiddle.net/B7P65/for reference. I'm trying to replace the parent div with the 'highlight' div, so i thought the toggle div would work. When the checkbox is deselected, I would like the background color to go back to normal (or remove the 'highlight' div). Any help is appreciated.
我正在尝试更改带有复选框的 div 的背景颜色。我做了这个http://jsfiddle.net/B7P65/以供参考。我正在尝试用“突出显示”div 替换父 div,所以我认为切换 div 会起作用。取消选中复选框后,我希望背景颜色恢复正常(或删除“突出显示”div)。任何帮助表示赞赏。
回答by RobB
You are using the parent()method incorrectly. You want to extract the toggleClass()
method from within the parent()
method and place it separately.
您错误地使用了parent()方法。您想toggleClass()
从parent()
方法中提取方法并将其单独放置。
Try the following update:
尝试以下更新:
$(this).parent().toggleClass("highlight");
Complete:
完全的:
$("input:checkbox").click(function() {
var actualTime = "";
$(this).parent().toggleClass("highlight");
});
回答by Tats_innit
Working Demohttp://jsfiddle.net/q3NN2/or ANother wayhttp://jsfiddle.net/KUhFp/
工作演示http://jsfiddle.net/q3NN2/或其他方式http://jsfiddle.net/KUhFp/
second demo shows how to use using .is(':checked')
just something extra if you want to use the is checked logic, :)
第二个演示展示了如何使用.is(':checked')
额外的东西,如果你想使用被检查的逻辑,:)
code
代码
$("input:checkbox").click(function() {
var actualTime = "";
$(this).parent().toggleClass("highlight");
});
code
代码
$("input:checkbox").click(function() {
var actualTime = "";
if ($(this).is(':checked')) {
$(this).parent().addClass("highlight");
} else {
$(this).parent().removeClass("highlight");
}
});
回答by czerasz
Try this: http://jsfiddle.net/B7P65/1/
试试这个:http: //jsfiddle.net/B7P65/1/
回答by Ramya
This code works for highlighting when checked and remove class when unchecked.
此代码用于在选中时突出显示并在未选中时删除类。
JavaScript:
JavaScript:
$('#your table id tr')
.filter(':has(:checkbox:checked)')
.addClass('highlight')
.end()
.click(function(event) {
$(this).toggleClass('highlight');
if (event.target.type !== 'checkbox') {
$(':checkbox', this).attr('checked', function() {
return !this.checked;
});
}
});
CSS:
CSS:
.highlight{
background-color:green;
}