jQuery迭代hover事件:图标组边框高亮仅首次正常,后续失效求助
It looks like the core issue here is that your current logic sometimes falls into the else branch (removing all active states) instead of only targeting the active element in the same group as the hovered item. Let's break down the fix step by step:
Root Cause
The else branch triggers only when refinementData is empty, which shouldn't happen if your hover event is bound directly to the <li> elements (since every valid <li> has data-identifier="refinement" or data-identifier="tag" from your Twig template). However, even when the if branch runs, your current loop checks all active elements and removes the class only if they match the current group—this works, but it's error-prone and unnecessary.
Fixed JavaScript Code
Replace your existing JS logic with this more targeted approach:
// Get the group type (refinement/tag) from the hovered element const currentGroup = el.dataset.identifier; // Only target active elements in the SAME group as the hovered item if (currentGroup) { parent.find(`${this.opts.control}.active[data-identifier="${currentGroup}"]`) .removeClass(this.opts.activeClass); } // Add active class to the currently hovered element el.classList.add(this.opts.activeClass);
Key Improvements
- Precise Targeting: Instead of looping through all active elements, we use an attribute selector (
[data-identifier="${currentGroup}"]) to directly find and remove the active class from only the element in the same group. This eliminates any chance of accidentally touching the other group's active state. - Removed Unnecessary Else Branch: Since every valid hover target (your
<li>icons) has adata-identifier, we can safely remove theelsebranch that was wiping all active states. This ensures the other group's active icon stays marked. - Clearer Variable Naming: Renamed
refinementDatatocurrentGroupto better reflect its purpose (it can hold either 'refinement' or 'tag').
Additional Checks
- Verify Event Binding: Make sure your hover event is attached directly to the
.option<li>elements, not their parent<div>or<ul>. If the event is on the parent,elwould be the parent element (which lacksdata-identifier), triggering the oldelsebranch. - Confirm Selector Values: Double-check that
this.opts.controlis set to.option(since all your icon<li>s have theoptionclass in the Twig template). If it's set to something else (like.svg-refinement), adjust the selector accordingly. - Initial State: Your Twig template correctly sets initial active states for both groups using
pre_config_refinementandpre_config_tag—this will work seamlessly with the fixed JS, as the initial active elements will be targeted correctly when hovering other items in their group.
With these changes, every hover will update only the active state in the hovered icon's group, keeping one active icon per group at all times.
内容的提问来源于stack exchange,提问作者Christoph

