Javascript 关于复选框检查的困惑

Javascript 关于复选框检查的困惑,javascript,jquery,loops,checkbox,prop,Javascript,Jquery,Loops,Checkbox,Prop,我有大约100门课程,带有带有classcourse 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

我有大约100门课程,带有带有class
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

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

从性能角度考虑,您的代码比迭代好

  • is的用法(“已检查”)
  • prop()的用法
  • 这两种情况必须进行迭代(循环检查是否已检查)

    如果您尝试使用迭代,那么代码可能会如下所示(这可以减少,但在我看到这篇文章后,我就想到了这一点)

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

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

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

    我认为您当前的解决方案是最好的。
    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;
    }