如果复选框被选中,请执行此操作 [英] if checkbox is checked, do this
问题描述
当我选中一个复选框时,我希望它变成
#0099ff
.
When I check a checkbox, I want it to turn <p>
#0099ff
.
当我取消选中复选框时,我希望它撤消那个.
When I uncheck the checkbox, I want it to undo that.
我到目前为止的代码:
$('#checkbox').click(function(){
if ($('#checkbox').attr('checked')) {
/* NOT SURE WHAT TO DO HERE */
}
})
推荐答案
我会使用 .change()
和 this.checked
:
$('#checkbox').change(function(){
var c = this.checked ? '#f00' : '#09f';
$('p').css('color', c);
});
--
关于使用 this.checked
Andy E 写了一篇关于我们如何过度使用 jQuery 的精彩文章:利用 jQuery 的强大功能来访问元素的属性.文章专门处理了 .attr("id")
的使用,但是在 #checkbox
is 一个 元素
$(...).attr('checked')
(甚至 $(...).is(':checked')
) 对比 this.checked
.
On using this.checked
Andy E has done a great write-up on how we tend to overuse jQuery: Utilizing the awesome power of jQuery to access properties of an element. The article specifically treats the use of .attr("id")
but in the case that #checkbox
is an <input type="checkbox" />
element the issue is the same for $(...).attr('checked')
(or even $(...).is(':checked')
) vs. this.checked
.
这篇关于如果复选框被选中,请执行此操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!