当我选中一个复选框时,我希望它变成<p> #0099ff.

When I uncheck the checkbox, I want it to undo that.

Code I have so far:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 

推荐答案

I would use .change() and this.checked:

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

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.

Jquery相关问答推荐

如何根据另一个 radio Select 并切换?

jQuery在localStorage时将类添加到正文

通过 .push() 方法向对象添加项目

jQuery:使用变量作为 Select 器

在 CSS3 或 jQuery 中将元素的宽度从 0% 设置为 100% 动画,它和它的包装器只需要它们需要的宽度,没有预先设置的宽度

将一个类动态添加到 Bootstrap 的popover容器中

如何使用 jQuery 获取所有 ID?

如何使用jQuery删除父元素

获取单选按钮组的值

如何使用 jQuery 重置 jquery Select 的 Select 选项?

如何在 HTML选项标签上显示工具提示?

延期与promise

为什么找不到我的 json 文件?

从父 node 中删除所有子 node ?

移动 chrome 在滚动时触发调整大小事件

Underscore.js 和 jQuery 互补吗?

jQuery - 确定输入元素是文本框还是 Select 列表

5秒后jQuery自动隐藏元素

你会如何比较 jQuery 对象?

jquery - 成功时使用ajax结果返回值