关于复选框检查的困惑

Confusion about checkbox-checking

本文关键字:检查 复选框      更新时间:2023-09-26

我有大约100门带有复选框的课程,其中有course-chkbox类,我使用以下代码:

//Make sure user has checked at least one course        
if ($('.course-chkbox:checked').length === 0) {
    alert('You have to have at least one course selected');
    return false;
}

基于我使用的是最新版本的jQuery,这是正确的吗?

基于一些谷歌搜索,有很多关于如何解决同样问题的建议。。。

     1. Usage of is("checked")
     2. Usage of prop()
     3. Looping through the elements involved and check each element if it's checked

什么解决方案是最好的,为什么?

考虑到性能,您的代码比迭代更好。

  1. is的用法("checked")
  2. prop()的用法

这两种情况必须进行迭代(循环检查是否已检查)

$('.course-chkbox').is(':checked').length // returns undefined
$('.course-chkbox').prop('checked').length //returns undefined

如果你尝试使用迭代,那么代码可能看起来像

var tot;
$('.course-chkbox').each(function() {
  if ($(this).is(':checked')) { //or if($(this).prop('checked')) {
    tot = tot + 1;
  }
});
if (tot == 100) {
  alert('You have to have at least one course selected');
  return false;
}

因此,使用您的代码是明智的。

if ($('.course-chkbox:checked').length) {
    alert('You have to have at least one course selected');
    return false;
}

我试图为这个测试用例创建基准(您的代码获胜),但不确定代码的正确性。