【问题标题】:Confusion about checkbox-checking [closed]关于复选框检查的困惑[关闭]
【发布时间】:2013-11-20 10:29:20
【问题描述】:

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

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

【问题讨论】:

  • 我认为您当前的解决方案是最好的。

标签: javascript jquery loops checkbox prop


【解决方案1】:

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

  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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 2015-10-16
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2020-03-06
    • 2016-03-16
    相关资源
    最近更新 更多