jQuery hover事件异常:多.prices1元素hover时箭头按钮全显求助
Hey there! I see the issue you're facing—right now, when you hover any <a> inside a .prices1 block, jQuery is selecting all .arrow elements on the page, which is why both arrows show up at once. Let's fix this by targeting only the elements within the hovered block.
The Problem with Your Current Code
Your code uses $('.arrow') and $('.button-tarieven p'), which are global selectors. They don't care which .prices1 block the hover came from—they just grab every matching element on the page.
Solution 1: jQuery with Scoped Selection
We'll use $(this) to reference the specific <a> being hovered, then use .closest('.prices1') to find its parent .prices1 container. From there, we'll only modify elements inside that container:
$(".prices1 a").hover(function () { // Get the parent .prices1 block of the hovered link const $currentBlock = $(this).closest('.prices1'); // Update only the arrow in this block $currentBlock.find('.arrow').css({ "opacity": "100%", "transform": "translate(0%, -80%)" }); // Update only the button text in this block (note: your HTML uses .buttons-price, not .button-tarieven—fix that class name if needed!) $currentBlock.find('.buttons-price p').css({ "transform": "translateY(-50%)", "opacity": "0%" }); }, function () { const $currentBlock = $(this).closest('.prices1'); $currentBlock.find('.arrow').css({ "transform": "translate(0%, 0%)", "opacity": "0%" }); $currentBlock.find('.buttons-price p').css({ "transform": "translateY(0%)", "opacity": "100%" }); });
Quick Note on Class Names
I noticed your HTML uses .buttons-price for the button container, but your original code references .button-tarieven—make sure those class names match to avoid issues!
Solution 2: CSS-Only (More Efficient)
For better performance and cleaner code, you could ditch jQuery entirely and use CSS hover states. This works because CSS can target elements within the hovered parent block:
/* Default styles for arrow and button text */ .prices1 .arrow { opacity: 0; transform: translate(0%, 0%); transition: all 0.3s ease; /* Add smooth animation */ } .prices1 .buttons-price p { opacity: 1; transform: translateY(0%); transition: all 0.3s ease; } /* Hover state: Target elements inside the hovered .prices1 block */ .prices1:hover .arrow { opacity: 1; transform: translate(0%, -80%); } .prices1:hover .buttons-price p { opacity: 0; transform: translateY(-50%); }
If you only want the effect to trigger when hovering the <a> tag (not the entire block), adjust the CSS selector to target the hovered link and its siblings:
/* Trigger when hovering the "Make appointment" link */ .prices1 .buttons-price a:hover ~ a .arrow { opacity: 1; transform: translate(0%, -80%); } .prices1 .buttons-price a:hover p { opacity: 0; transform: translateY(-50%); }
Either solution will fix your issue—pick whichever fits your workflow best!
内容的提问来源于stack exchange,提问作者Marc Bacher

