使用jQuery检查是否至少选中了一个复选框

编程入门 行业动态 更新时间:2024-10-23 23:26:00
本文介绍了使用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检查是否至少选中了一个复选框

本文发布于:2023-11-04 01:02:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复选框   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!