jQuery:如何只选择可见和检查的复选框?

Bog*_*dan 6 jquery

我正在尝试检查某个系列中的所有可见复选框是否都已经过检查,我想只计算那些可见的和那些可见的并检查以查看数字是否相同.问题是我无法使可见或选中的选择器工作.

这些是我的一些想法,但没有奏效:

if($j("input[id^='chk_camp']:visible:checked").length == $j("input[id^='chk_camp']:visible").length)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,双方都是0

if($j("input[id^='chk_camp']").filter(':visible').filter(':checked').length == $j("input[id^='chk_camp']").filter(':visible').length)
Run Code Online (Sandbox Code Playgroud)

双方也回归0.

也试过了

if($j("input[id^='chk_camp'][visible][checked]").length == $j("input[id^='chk_camp'][visible]").length)
Run Code Online (Sandbox Code Playgroud)

这也是双方都返回0.

作为注释$j("input[id^='chk_camp']").length返回正确的值.我正在使用的浏览器是Firefox.

我在这做错了什么?

答:很明显,我做错了就是别的地方.在实际制作包含复选框的div之前,我正在进行这些检查,因此所有可见性检查都返回false.

Joo*_*nas 7

你可以这样做:

的jsfiddle

jQuery的:

$('input').each(function() {

    // If input is visible and checked...
    if ( $(this).is(':visible') && $(this).prop('checked') ) {

        $(this).wrap('<div />');

    }

});
Run Code Online (Sandbox Code Playgroud)

HTML:

<input type="checkbox" checked="checked">
<input type="checkbox" checked="checked" style="display: none;">
<input type="checkbox">
<input type="checkbox" checked="checked" style="display: none;">
<input type="checkbox" checked="checked">
<input type="checkbox">
Run Code Online (Sandbox Code Playgroud)

CSS:

div { float: left; background: green; }
div input { display: block !important; }
Run Code Online (Sandbox Code Playgroud)


小智 6

这对我来说很好.

$(".inputClass:checked:visible");
$(".inputClass:checked:visible").length;
Run Code Online (Sandbox Code Playgroud)

或适应上述答案.

的jsfiddle

$('input:visible:checked').each(function() {
    $(this).wrap('<div />');
});
Run Code Online (Sandbox Code Playgroud)