我正在尝试创建一个多重过滤器,该过滤器在单击复选框后会显示相关元素。选中绿色复选框后,应显示绿色div,单击绿色和红色复选框后,应显示具有绿色和红色类别的div,否则不显示。单击复选框后,我已将复选框类存储在数组中。
<script>
var classname = [];
$( function () {
$( '.check' ).change( function () {
if ( $( this ).is( ':checked' ) ) {
// $( '.main div' ).css( 'display', 'none' );
classname.push( ( this ).className );
console.log( classname );
}
if ( $( this ).is( ':checked' ) == false ) {
classname.pop( ( this ).className );
};
} );
} );
$( '#clear' ).on( 'click', () => {
$( '.check' ).prop( 'checked', false );
classname.length = 0;
} );
</script>
<div class="container grid">
<div class="sidebar">
<input type="checkbox" class="green check">Green
<input type="checkbox" class="blue check">Blue
<input type="checkbox" class="red check">Red
<input type="checkbox" class="yellow check">Yellow
<input type="button" value="Clear" id="clear">
</div>
<div class="main">
<div class="green yellow">Green Yellow</div>
<div class="blue red"></div>
<div class="yellow"></div>
<div class="blue"></div>
<div class="green"></div>
<div class="green red">Green Red</div>
<div class="red yellow">Red Yellow</div>
<div class="yellow blue">Yellow Blue</div>
<div class="red green">Red Green</div>
</div>
</div>
var classname = [];
$( function () {
$( '.check' ).change( function () {
if ( $( this ).is( ':checked' ) ) {
// $( '.main div' ).css( 'display', 'none' );
if((this).className){
classname.push((this).className.split(' ')[0].trim());
$( '.main div' ).each(function() {
$(this).css('display','none');
var block = this;
classname.forEach(function(value,index,array){
if(block.className.includes(value)){
$(block).css('display','block');
}
});
});
}
}
if ( $( this ).is( ':checked' ) == false ) {
classname.pop( ( this ).className );
};
} );
} );
$( '#clear' ).on( 'click', () => {
$( '.check' ).prop( 'checked', false );
classname.length = 0;
$( '.main div' ).each(function() {
$(this).css('display','block');
});
} );
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="container grid">
<div class="sidebar">
<input type="checkbox" class="green check">Green
<input type="checkbox" class="blue check">Blue
<input type="checkbox" class="red check">Red
<input type="checkbox" class="yellow check">Yellow
<input type="button" value="Clear" id="clear">
</div>
<div class="main">
<div class="green yellow">Green Yellow</div>
<div class="blue red">Blue Red</div>
<div class="yellow">Yellow</div>
<div class="blue">Blue</div>
<div class="green ">Green</div>
<div class="green red">Green Red</div>
<div class="red yellow">Red Yellow</div>
<div class="yellow blue">Yellow Blue</div>
<div class="red green">Red Green</div>
</div>
</div>
我已经对您的代码进行了一些更改。检查是否可以回答您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句