2013-11-20 73 views
0

我有几分大约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 

什么解决办法是最好的,为什么?

+2

我认为你现在的解决方案是最好的。 – NoLifeKing

回答

2

考虑到性能明智,你的代码比迭代更好。的

  1. 用法是( “选中”)丙()

这些2案件

  • 用法必须经历迭代(循环通过判断是否是选中)。

    $('.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; 
    } 
    

    我试图为这个测试用例创建benchmark(您的代码胜),不知道代码的正确性。