如果复选框被选中,请执行此操作 [英] if checkbox is checked, do this

查看:38
本文介绍了如果复选框被选中,请执行此操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我选中一个复选框时,我希望它变成

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆