IE11中.addClass方法失效问题及相关代码求助
Let's break down the issues in your code and fix them step by step—IE11 has some quirks, but the main problem here is a logical error in your condition that's causing unexpected behavior across all browsers (not just IE11).
1. Fix the Broken Conditional Logic
Your current condition !buttonYears.indexOf(yearBtn) !== -1 is logically incorrect and will almost always evaluate to true, meaning you're hiding buttons you shouldn't. Here's why:
indexOfreturns-1if the value isn't found, or a non-negative index if it is.- The
!operator negates the result:!(-1)isfalse(since-1is truthy),!0istrue(since0is falsy), and!5isfalse(since5is truthy). - Comparing that result to
-1(false !== -1ortrue !== -1) will always betrue.
You want to hide buttons whose year isn't in buttonYears, so replace that condition with:
if (buttonYears.indexOf(yearBtn) === -1) { $(this).addClass('hidden'); }
2. Ensure Type Matching Between yearBtn and buttonYears
IE11 is strict about type equality, so if yearBtn is a string (from input.val()) but buttonYears contains numbers (from your Lodash map), indexOf won't find a match even if the values are the same.
Fix this by converting yearBtn to a number (if your years are numeric):
var yearBtn = parseInt($(this).find('input').val(), 10);
Or, if your years are stored as strings in buttonYears, keep yearBtn as a string (no conversion needed).
3. Verify buttonYears is an Array
Double-check that window.availableButtonYears is actually an array (Lodash's _.uniq should return an array, but it's good to confirm). Add a console log to debug:
console.log("buttonYears:", buttonYears, "Type:", typeof buttonYears);
If it's not an array, adjust your Lodash chain to ensure it returns an array of year values.
Corrected Full Function
Here's the revised function with all fixes applied:
function redrawButtonToolbar() { var buttonYears = window.availableButtonYears; console.log("buttonYears:", buttonYears); // Debug log $(".year-btn").removeClass('hidden').each(function(index) { var yearBtn = $(this).find('input').val(); console.log("Current yearBtn:", yearBtn); // Debug log if(yearBtn === 'all') { return; // Skip the "all" button } // Convert to number if buttonYears contains numeric values yearBtn = parseInt(yearBtn, 10); if(buttonYears.indexOf(yearBtn) === -1) { $(this).addClass('hidden'); } }); }
Final Checks for IE11
- Make sure you're using a version of jQuery that supports IE11 (jQuery 3.x dropped IE11 support, so use 2.x if needed).
- Confirm your
.hiddenCSS class is properly defined (e.g.,.hidden { display: none; }).
内容的提问来源于stack exchange,提问作者GettingStarted

