通过多个下拉列表过滤内容



我有 2 个下拉列表,它们分别过滤内容。如果所选选项位于div 中,则会显示该div。

如何同时使用它们来过滤内容?我想要的只是让这两个下拉列表一起工作。他们目前正在单独过滤内容。因此,如果下拉列表 1 单独过滤内容 ABCDE,而下拉列表 2 过滤内容 DEG(如果两者都被选中(,则显示的内容应为 DE

$(document).ready(function(){
$('#level').on('change', function() {
var val = $(this).val();
if ( val == '00'){
$(".textIc").show();
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(val) !==-1){
$(this).show();
}else{
$(this).hide();
}
});
}
});
$('#type').on('change', function() {
var val = $(this).val();
if ( val == '000'){
$(".textIc").show();
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(val) !==-1){
$(this).show();
}else{
$(this).hide();
}
});
}
});
});
div {
border: 1px solid black;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select id="level">
<option value="00" selected><b>Default</b></option>
<option value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Primary and Secondary">Primary and Secondary</option>
</select>
<select id="type">
<option value="000" selected><b>Default</b></option>
<option value="King">King</option>
<option value="Queen">Queen</option>
</select>
<div class="textIc">
<p>Primary</p>
<p>King</p>
</div>
<div class="textIc">
<p>Secondary</p>
</div>
<div class="textIc">
<p>Primary and Secondary</p>
<p>King</p>
<p>bla bla bla bla</p>
</div>
<div class="textIc">
<p>Primary</p>
<p>Queen</p>
</div>
<div class="textIc">
<p>Secondary</p>
</div>
<div class="textIc">
<p>Primary and Secondary</p>
<p>King</p>
<p>bla bla bla bla</p>
</div>

这是小提琴。

以下是考虑这两个下拉列表的代码。

$(document).ready(function(){
$('#level').on('change', function() {
var val = $(this).val();
var typeVal = $('#type').val();
if ( val == '00'){
if(typeVal == '000'){
$(".textIc").show();
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(typeVal)!==-1){
$(this).show();
}else{
$(this).hide();
}
});
}
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(val) !==-1 && (typeVal=='000' || $(this).children("p").text().indexOf(typeVal)!==-1)){
$(this).show();
}else{
$(this).hide();
}
});
}
});
});
$(document).ready(function(){
$('#type').on('change', function() {
var val = $(this).val();
var levelVal = $('#level').val();
if ( val == '000'){
if(levelVal == '00'){
$(".textIc").show();
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(levelVal)!==-1){
$(this).show();
}else{
$(this).hide();
}
});
}
}else{
$('.textIc').each(function(){
if($(this).children("p").text().indexOf(val) !==-1 && (levelVal=='00' || $(this).children("p").text().indexOf(levelVal)!==-1)){
$(this).show();
}else{
$(this).hide();
}
});
}
});
});

这是测试的小提琴。

基本思路
检查每个下拉列表的change事件中的两个下拉列表值。

注意:上面的代码可以重构以减少if语句的数量。并且使用.each()循环遍历每个元素可以移动到单独的function()

最新更新