/ / nullではない各文字列のjQueryフィルター-javascript、jquery、filter

nullでない各文字列のjQueryフィルタ - javascript、jquery、filter

nullではないすべての文字列にjQueryフィルターを適用するにはどうすればよいですか?

基本的に、次のコードがあり、事前に設定されている任意の数の「セレクター」で動作するようにしたいと思います。

使用可能なセレクターのリストは配列になります。

if (typeselector === "" && colorselector === "") {
$(".product").filter(selector).show();
} else if (typeselector === "") {
$(".product").filter(selector).filter(colorselector).show();
} else if (colorselector === "") {
$(".product").filter(selector).filter(typeselector).show();
} else {
$(".product").filter(selector).filter(typeselector).filter(colorselector).show();
}

提案/ヘルプをありがとう!

回答:

回答№1は1

単純化するには、連鎖を使用できます。

var products = $(".product").filter(selector);
if (typeselector !== "") {
products = products.filter(typeselector);
}
if (colorselector !== "") {
products = products.filter(colorselector);
}
products.show();

またはこのようなものであっても:

var products = $(".product").filter(selector);
var selectors = [typeselector, colorselector];

selectors.each(function(selector) {
if (selector !== "") {
products = products.filter(selector);
}
});
products.show();