基于jQuery的多值data-genre图片过滤功能修复需求
Fixing jQuery Image Filter for Multi-Value data-genre Attributes
Hey there, let's fix that multi-genre filtering issue you're facing. The core problem in your current code is how you're checking the data-genre attribute, plus there's a small bug in your year filtering logic. Here's how to adjust things without rewriting your whole code:
Modified Complete JavaScript Code
$('select.type, select.genre, select.year, select.season, select.status').change(updateCategories); function updateCategories() { // Get all filter values var caType = $('select.type').val(); var caGenre = $('select.genre').val(); var caYear = $('select.year').val(); var caSeason = $('select.season').val(); var caStatus = $('select.status').val(); $('.ps-page') .find('.ps-links') .hide() .filter(function () { var okcaType = true; if(caType !== "all"){ okcaType = $(this).attr('data-type') === caType; } var okcaGenre = true; if(caGenre !== "all"){ // Split multi-value genre string into a clean array var genres = $(this).attr('data-genre').split(',').map(item => item.trim()); // Check if selected genre exists in the array okcaGenre = genres.includes(caGenre); } var okcaYear = true; if(caYear !== "all"){ // Fixed: Use attr() to get data-year instead of incorrect filter() okcaYear = $(this).attr('data-year') === caYear; } var okcaSeason = true; if(caSeason !== "all"){ okcaSeason = $(this).attr('data-season') === caSeason; } var okcaStatus = true; if(caStatus !== "all"){ okcaStatus = $(this).attr('data-status') === caStatus; } // Only show items that meet all active filter criteria return okcaType && okcaGenre && okcaYear && okcaSeason && okcaStatus; }).fadeIn('fast'); }
How It Works
- Multi-Value Genre Handling:
- We split the
data-genrestring into an array usingsplit(',') - Since your genre values have spaces after commas (like
"sci-fi, police"), we usemap(item => item.trim())to remove extra whitespace from each genre entry - The
includes()method checks if the selected genre is present in the cleaned array—this works for both single-value and multi-valuedata-genreattributes
- We split the
- Fixed Year Filter: Your original code used
$(this).filter('data-year')which is incorrect (.filter()is for selecting DOM elements, not getting attributes). We replaced it with$(this).attr('data-year')to properly compare year values.
This change keeps your existing code structure intact while fixing both the multi-genre filtering and the hidden year filter bug.
内容的提问来源于stack exchange,提问作者karthik
相关产品推荐
相关产品推荐

