我想判断当用户点击复选框时,复选框是否被取消选中.这是因为我想在用户取消选中复选框时进行验证.因为至少需要选中一个复选框.因此,如果他取消选中最后一个,那么它会自动再次判断自己.

使用jQuery,我可以很容易地找到它是否已被判断:

$('#check1').click(function() {
    if($(this).is(':checked'))
        alert('checked');
    else
        alert('unchecked');
});

但我实际上只想有一个if语句来判断复选框是否被取消选中.

所以我想我可以用下面的代码做到这一点:

$('#check2').click(function() {
    if($(this).not(':checked'))
        alert('unchecked');
    else
        alert('checked');
});

But this will always show the 'unchecked' message. Not really what i was expecting...

demo: http://jsfiddle.net/tVM5H/

So eventually i need something like:

$('#check2').click(function() {
    if($(this).not(':checked')) {
        // Got unchecked, so something!!!
    }
});

But obviously this doesn't work. I rather don't want to use the first example, because then i'd have an unnecessary 'else' statement when i only need one 'if' statement.

So first thing, is this a jQuery bug? Cause to me it's unexpected behaviour. And second, anyone any ides for a good alternative?

推荐答案

Try this:

if(!$(this).is(':checked'))

demo

Jquery相关问答推荐

在 JQuery DataTable 中通过按钮单击传递 ID

如何用 jQuery / AJAX 替换表格的行

为什么我的 toFixed() 函数不起作用?

如何获取将在不提交的情况下提交的所有表单值

jQuery函数从数组中获取所有唯一元素?

如何在 jQuery Select 器中定义 css :hover 状态?

TypeScript 中是否有this的别名?

纯css关闭按钮

在 select2 中使用 AJAX 进行标记

如何使用 jQuery go 除 HTML 标签?

jQuery JSON到字符串?

如何使用 jQuery 显示忙碌指示器?

jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

如何在我的 WordPress 插件中包含 CSS 和 jQuery?

循环判断复选框并计算每个选中或未选中的复选框

如何获得元素的正确偏移量? - jQuery

Bootstrap 4 文件输入

Fancybox 不适用于 jQuery v1.9.0 [ f.browser 未定义 / 无法读取属性 'msie' ]

'touchstart' 事件是否有与点击事件相同的 e.PageX 位置?

如何使用 JQuery 删除onclick?