我想按类过滤(显示/隐藏)元素。我想让我们说 5 个过滤器一起工作。
<select id='filter4'>...</select>
<select id='filter5'>...</select>
<select id='filter6'>...</select>
<select id='filter7'>...</select>
和
<select id='filter6' multiple>...</select>
jQuery:
jQuery(document).ready(function ($) {
$("select").on("change", function () {
var filterVal = $("select#filter4").val();
var filterVal2 = $("select#filter5").val();
var filterVal3 = $("select#filter6").val();
var filterVal4 = $("select#filter7").val();
var filterVal5 = $("select#filter8").val();
var filterSelector = "";
var filter2Selector = "";
var filter3Selector = "";
var filter4Selector = "";
var filter5Selector = "";
if (filterVal == "all" && filterVal2 == "all" && filterVal3 == "all" && filterVal4 == "all" && filterVal5 === null) {
//show all items
$(".item").fadeIn("fast");
} else {
if (filterVal != "all") {
filterSelector = "." + filterVal;
}
if (filterVal2 != "all") {
filter2Selector = "." + filterVal2;
}
if (filterVal3 != "all") {
filter3Selector = "." + filterVal3;
}
if (filterVal4 != "all") {
filter4Selector = "." + filterVal4;
}
if (filterVal5 !== null) {
filter5Selector = "." + filterVal5;
}
$(".item").hide();
$(filterSelector + filter2Selector + filter3Selector + filter4Selector + filter5Selector).fadeIn("fast");
}
});
});
前四个单个过滤器可以解决任何问题。选择多个选项时,第五个多选择元素无法正常工作(过滤)。
编辑:需要在全局匹配的 g 修饰符 (/ /g) 的帮助下用点(多个 css 选择器)替换逗号:
$(filter4Selector + filter5Selector.replace(/,/g, ".")).fadeIn("fast");
见http://jsfiddle.net/mahish/dum7n/。
下面的答案提供了同样有效的不同代码!