如下为4选2的例子:
<div class="check flex">
<div><input type="checkbox" name="checkone" id="check-one" value="one"><label for="check-one">one</label></div>
<div><input type="checkbox" name="checktwo" id="check-two" value="two"><label for="check-two">two</label></div>
<div><input type="checkbox" name="checkthree" id="check-three" value="three"><label for="check-three">three</label></div>
<div><input type="checkbox" name="checkfour" id="check-four" value="four"><label for="check-four">four</label></div>
</div>
jq代码:
let count = 0;
$('.check input').click(function() {
let c1 = $(this).prop('checked'); // 获取点击选项是否选中,值为true与false
let total = $('.check').children().length; // 获取子元素的数量
if(c1) { // 如果选中
count++;
$(this).addClass('active');
}
else {
count--;
$(this).removeClass('active');
}
if(count >= 2) { // 选中数量大于2
for(let i = 0; i < total; i++) {
if(!$('.check div').eq(i).children('input').hasClass('active')) {
$('.check div').eq(i).children('input').prop('disabled', true); // 将未选中的input禁用
}
}
}
else {
for(let i = 0; i < total; i++) {
$('.check div').eq(i).children('input').removeAttr('disabled'); // 移除禁用
}
}
})
演示图:
以上。