2015-10-15 35 views
0

檢測複選框的可見性狀態時出現問題,我想要求您的幫助。.is(「:visible」)find

我的頁面,它看起來像一個dynamicaly加載部分:

<div id="box"> 

    <div class="colored"> 
    <input type="checkbox" value="f01" name="mycheckbox"> 
    <!-- some content --> 
    <div> 

    <div class="colored"> 
    <input type="checkbox" value="f02" name="mycheckbox"> 
    <!-- some content --> 
    <div> 

    <!-- .... --> 


</div> 

這表示,我們應該說,在一些庫項目。每班=「彩色」div可以是可見或隱藏的。 可以說,這是簡單的過濾器,就像我希望有明顯的唯一一類=「有色黃」的div

而現在問題的核心: 我需要通過整個BOX元素循環,找到所有複選框後通過每個複選框,「問他」,如果它是可見的,如果是真的,檢查他。

Unforunately,這不起作用:

function checkallfav() { 
    $("#box").find('input[type=checkbox]').each(function() { 
     if (this.is(":visible")) { 
      this.checked = true; 
     } 
    }); 
} 

//And this doesn't work as well 
function checkallfav() { 
    $("#box").find('input[type=checkbox]').is(":visible").each(function() { 
     this.checked = true; 
    }); 
} 

的問題是,FIND函數返回整個元素,我想 Console.debug(本);並在螢火蟲,響應是所有html元素

所以,請,任何人都有一個解決方案?

+1

您需要使用'$(本)。是( 「:可見」)' – Satpal

+0

由於兩個答案表明,無論是你的方法可能* *已經工作,你只是在兩個小錯誤。 – Jamiec

回答

4

在複選框本身上使用:visible選擇器。在選擇器上使用:visible將只過濾可見元素,然後可以在這些複選框上直接使用prop

$("#box").find('input[type=checkbox]:visible').prop('checked', true); 

的代碼也可以縮短爲

$('#box :checkbox:visible').prop('checked', true); 
2

這裏this是指原生DOM對象,他們沒有.is()功能的jQuery的功能,從而有jQuery對象使用。因此應該使用$(this).is(":visible")

$("#box").find('input[type=checkbox]').each(function() { 
    if ($(this).is(":visible")) { 
     this.checked = true; 
    } 
}); 

更簡單的方法來實現是通過使用@圖莎爾的建議

1

你可以使用prop()函數的參數過:

$("#box").find(':checkbox').prop('checked',function(){ 
    return $(this).is(':visible'); 
}); 

這將由方式取消任何隱藏的複選框(如果需要) 。

0

這可以用.filter()方法來實現:

$("#box").find('input[type=checkbox]').filter(':visible').prop('checked', true);