【发布时间】:2012-11-02 15:35:40
【问题描述】:
我有三个复选框,如果选中其他两个中的一个和/或其中一个,则需要禁用第三个。我敢肯定有比我目前更简单的方法。它正在变成我认为是一团糟,我希望有更多 jquery 知识的人可以在这里发光。
这是我的简单 html 表单:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<input type="checkbox" class="class" id="1">First
<input type="checkbox" class="class" id="2">Second
<input type="checkbox" class="class" id="3">Third
</body>
</html>
这是我在 jquery v1.4.2 中使用的 javascript
jQuery(document).ready(function() {
// watches the events of all checkboxes
$(":checkbox").click(function(){
if(
// if both 1 and 2 are checked we don't want to enable Third until both are unchecked.
(($('#1:checkbox').attr('checked'))&&($('#2:checkbox').attr('checked')))||
((($('#1:checkbox').attr('checked'))&&($('#2:checkbox').attr('checked')))&&($('#3:checkbox').attr('disabled')))||
((($('#1:checkbox').attr('checked'))||($('#2:checkbox').attr('checked')))&&($('#3:checkbox').attr('disabled')))
){
// we don't want to do anything in the above events
} else if(
// handles the First check box
(($('#1:checkbox').attr('checked'))||(!$('#1:checkbox').attr('checked')))||
// handles the Second check box
(($('#2:checkbox').attr('checked'))||(!$('#2:checkbox').attr('checked')))
){
// call the disableThird function
disableThird();
}
});
// handles enabling and disabling the Third checkbox
function disableThird(){
var $checkbox = $('#3:checkbox');
$checkbox.attr('disabled', !$checkbox.attr('disabled'));
};
});
出于某种原因,检查 #3 将禁用它的自身。我不明白为什么。
这可行,但其中一个要求是非程序员应该能够编辑和维护它。理想情况下,如果他可以在 html 中添加新的复选框并且它会起作用,那就太好了。这些类是定义的,据我所知无法更改。如果选择了上述任何一个复选框,则复选框列表中的最后一个复选框将被禁用。同样,如果选中最后一个复选框,它将禁用其上方的所有复选框。我什至还没有开始编写和测试那部分,因为这对于非程序员来说很快就变得太复杂了。我自己更像是一个 PHP 编码器而不是一个 js,更不用说 jquery 编码器了。任何帮助将不胜感激。
【问题讨论】: