2013-11-20 75 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(您的代碼勝),不知道代碼的正確性。