使用jQuery检查是否至少选中了一个复选框 [英] Check if at least one checkbox is checked using jQuery

查看:49
本文介绍了使用jQuery检查是否至少选中了一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有五个复选框.使用jQuery,如何检查其中至少一项被选中?

I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?

<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">

推荐答案

此答案中的原始解决方案效率低下,不应使用.请根据此问题的其他答案的评论和示例查看修订后的解决方案.

The original solution in this answer is inefficient and should not be used. Please see the revised solution based on comments and examples from other answers to this question.

原始(不良)解决方案如下:

The original (bad) solution follows:

// DO NOT USE; SEE BELOW
$('button').click(function () {
  var atLeastOneIsChecked = false;
  $('input:checkbox').each(function () {
    if ($(this).is(':checked')) {
      atLeastOneIsChecked = true;
      // Stop .each from processing any more items
      return false;
    }
  });
  // Do something with atLeastOneIsChecked
});

在此示例中,.each()的使用是多余的,因为.is()可以直接在一组对象上使用,而不是手动遍历每个对象.一个更有效的解决方案如下:

The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one. A more efficient solution follows:

$('button').click(function () {
  var atLeastOneIsChecked = $('input:checkbox').is(':checked');
  // Do something with atLeastOneIsChecked
});

请注意,其中一项注释表示对$(this).is(':checked')的强烈不满.需要说明的是,在测试一组对象的情况下,is(':checked')没什么问题.也就是说,在单个项目上调用is(':checked')的效率要比在同一项目上调用.checked的效率低得多.它还涉及到对$函数的不必要调用.

Note that one of the comments indicates a strong dislike for $(this).is(':checked'). To clarify, there is nothing wrong with is(':checked') in cases where you are testing a set of objects. That said, calling is(':checked') on a single item is much less efficient than calling .checked on the same item. It also involves an unnecessary call to the $ function.

这篇关于使用jQuery检查是否至少选中了一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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