2012-01-07 39 views
0

的示例代码使用jQuery来防止用户取消选中,最后选中的复选框。它在Firefox和Chrome中按预期运行,但不在Opera或IE中运行。复选框和JQuery举止异常在Opera和IE

<!DOCTYPE html> 
<html> 
<head> 
    <style type="text/css"> 
     #checkboxContainer label { 
      float: left; 
      clear: right; 
     } 
     #checkboxContainer input { 
      float: left; 
      clear: left; 
     } 
    </style> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("#checkboxContainer input[type='checkbox']").change(function(evt) { 
       if ($("#checkboxContainer input[type='checkbox']:checked").length == 0) { 
        console.log("Only 1 checkbox; can't uncheck."); 
        $(evt.target).attr("checked", "checked"); 
       } 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <div id="checkboxContainer"> 
     <input type="checkbox" id="checkbox1" checked="checked"/> 
     <label for="checkbox1">1</label> 
     <input type="checkbox" id="checkbox2"/> 
     <label for="checkbox2">2</label> 
    </div> 
</body> 
</html> 

这是怎么回事?

回答

1

这似乎在IE和Opera工作,如果你改变你的选择器“:勾选”而不是“输入[类型=‘复选框’]”。 jQuery文档声明两者是等价的,所以我不确定如何解释行为的差异。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#checkboxContainer :checkbox").change(function(evt) { 
      if ($("#checkboxContainer :checkbox:checked").length == 0) { 
       console.log("Only 1 checkbox; can't uncheck."); 
       $(evt.target).attr("checked", "checked"); 
      } 
     }); 
    }); 
</script> 
+0

感谢马特,这似乎工作,但我更感兴趣的是比解决方法的说明。 – 2012-01-07 05:22:20

+0

一个有趣的注意......我添加一个div,开始写计数进去,只是为了调试的目的,并补充说,导致原来的选择工作。然后,我删除了参考计数,只是设置一些静态的文本就行了DIV之前,“如果”在我上面的代码:$(“#debugDiv”)文本(“静态测试”),这也是固定的。问题。仍然不是一个解释 - 似乎可能需要更改DOM才能使用该选择器正确计算计数。 – Matt 2012-01-07 06:10:13

+0

非常感谢您进一步深入研究......它可能是一个JQuery错误。我完全困惑,因为这是一个非常基本的功能。 – 2012-01-07 06:26:31

0

您可以在此无错误:

<!DOCTYPE html> 
<html> 
<head> 
    <style type="text/css"> 
     #checkboxContainer label { 
      float: left; 
      clear: right; 
     } 
     #checkboxContainer input { 
      float: left; 
      clear: left; 
     } 
    </style> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
<script type="text/javascript"> 
     $(document).ready(function() { 
      $(".ceks").click(function() { 
       if(!$(".ceks:checked").length){ 
        $(this).attr("checked", "checked"); 
       } 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <div id="checkboxContainer"> 
     <input type="checkbox" class="ceks" checked="checked"/> 
     <label for="checkbox1">1</label> 
     <input type="checkbox" class="ceks"/> 
     <label for="checkbox2">2</label> 
    </div> 
</body> 
</html> 
+0

是的。似乎它有问题$(“。checkboxContainer输入[类型='复选框']:选中”),但输入:复选框:检查作品。 – 2012-01-07 22:23:59