如何在JavaScript的find函数中使用if语句,为不匹配元素添加类名?
Fixing Filter Logic for Adding 'filtered-out' Class in JavaScript
Hey there! Let's get your filtering logic sorted out. Your current code has a couple of misuses of map() and find() that are keeping it from working correctly. Let's break down the problem and fix it step by step.
What's Wrong With the Original Code?
map()is designed to transform array elements and return a new array, but you're using it to perform DOM side effects (adding a class).forEach()is the right tool here since we don't need to create a new array.find()expects its callback to return a boolean value, and it returns the first element that matches that condition. It's not meant to execute actions like adding classes directly in its callback.
Correct Implementation
Let's assume your goal is: Add the 'filtered-out' class to a car if it fails any of the active filter conditions (this is the most common filtering scenario). Here's how to do it properly:
// First, reset all cars to remove any existing filtered-out classes (optional but recommended) cars.removeClass("filtered-out"); // Iterate over each car to check filter conditions cars.forEach(car => { // Check if the car fails at least one filter condition const shouldFilter = active_filters.some(filter => { // Compare the car's attribute value to the filter's target value return car.attr(filter.id) !== filter.value; }); if (shouldFilter) { car.addClass("filtered-out"); } });
Key Explanations
some(): This method checks if at least one element in theactive_filtersarray satisfies the condition (car's attribute doesn't match the filter value). It returnstrueimmediately when it finds a mismatch, which is efficient.forEach(): Perfect for looping through thecarsarray to perform DOM operations (adding/removing classes) without needing to return a new array.- Resetting classes: Adding
cars.removeClass("filtered-out")ensures that if a car was previously filtered but now meets all conditions, the class gets removed.
If Your Goal is to Filter Only When All Conditions Fail
If you want to add the class only when the car doesn't match any of the filters (less common, but possible), swap some() with every():
const shouldFilter = active_filters.every(filter => { return car.attr(filter.id) !== filter.value; });
Note for Non-jQuery Users
If cars are native DOM elements instead of jQuery objects, modify the code to use native methods:
cars.forEach(car => { const shouldFilter = active_filters.some(filter => { return car.getAttribute(filter.id) !== filter.value; }); if (shouldFilter) { car.classList.add("filtered-out"); } else { car.classList.remove("filtered-out"); } });
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

