当jquery选中三个复选框时,如何使div变灰



我有一个页面,当选中三个复选框时,需要有一个div来淡出。我正在使用下面的代码,但它不起作用。有什么建议吗?

<script>
function countChecked() {
var n = $("input:checked").length;
if($("input:checked").length > 3) {
    }
    else
    {
   $(".chkExample")
     .fadeTo(500, 0.2)
    }
}
countChecked();

$(":checkbox").click(countChecked);

</script>

我对您的代码进行了一些格式化。这是在检查> 3。在这种情况下,这将与>= 4相同。所以你检查的是4个或更多,而不是3个或更多。

如果您想要恰好选中3个框,则需要执行n === 3。如果您想要3个或3个以上,请使用n >= 3,3个或以下,则使用n <= 3

此外,如果您只想在点击事件中选中该框,则不需要手动调用countChecked

此外,根据注释,使用一个局部变量来保存JQuery对象的长度。

此外,根据mcp的回答,使用[type="checkbox"]on方法。

结果:

function countChecked() {
    var n = $("input[type="checkbox"]:checked").length;
    if(n === 3) {
        $(".chkExample").fadeTo(500, 0.2)
    } else {
    }
}
$('input[type="checkbox"]').on('change', countChecked);​
function countChecked() {
    var count = $('input[type="checkbox"]:checked').length;
    // this will test for 3 or more >=
    if (count >= 3) { alert('3 or more checked!'); }
    else { $(".chkExample").fadeTo(500, 0.2) }
}
countChecked();
// assuming you are using at least 1.7.2 of jQuery
// but start using `.on()` and with checkboxes/radios I always use 'change'
$('input[type="checkbox"]').on('change', countChecked);​

现在从随机的角度来看:复选框实际上已经贬值了。使用[type="checkbox"],因为它无论如何都会使用本机javascript来加快速度。

jsFiddle演示

最新更新