You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

利用链接的Data Attribute切换上级容器Div的Class

解决:基于链接的data属性切换对应div的类

你的代码问题在于,breakoutClass变量是页面加载时从第一个带data-switch属性的元素上获取的值,并非当前鼠标悬停的那个链接的属性值——这导致所有链接触发hover时,都会给父div加上同一个类。

修正后的JS代码

$('.js-breakout-switch').hover(function() {
    // 获取当前hover链接的data-switch属性值
    const breakoutClass = $(this).data('switch');
    // 给父级的js-product-breakout元素切换对应类
    $(this).parents('.js-product-breakout').toggleClass(`show-${breakoutClass}`);
});

额外优化提示

如果需要鼠标移入时添加类、移出时移除类(而不是切换),可以把hover拆分成两个回调函数:

$('.js-breakout-switch').hover(
    // 鼠标进入
    function() {
        const cls = $(this).data('switch');
        $(this).parents('.js-product-breakout').addClass(`show-${cls}`);
    },
    // 鼠标离开
    function() {
        const cls = $(this).data('switch');
        $(this).parents('.js-product-breakout').removeClass(`show-${cls}`);
    }
);

完整代码示例

HTML

<div class="product-breakout js-product-breakout">
    <section class="breakout-item">
        <p class="breakout-item-text"><a class="breakout-item-link color-white js-breakout-switch" data-switch="01" href="#">View Part</a></p>
    </section>
    <section class="breakout-item">
        <p class="breakout-item-text"><a class="breakout-item-link color-white js-breakout-switch" data-switch="02" href="#">View Part</a></p>
    </section>
    <section class="breakout-item">
        <p class="breakout-item-text"><a class="breakout-item-link color-white js-breakout-switch" data-switch="03" href="#">View Part</a></p>
    </section>
</div>

JavaScript

$('.js-breakout-switch').hover(function() {
    const breakoutClass = $(this).data('switch');
    $(this).parents('.js-product-breakout').toggleClass(`show-${breakoutClass}`);
});

内容的提问来源于stack exchange,提问作者LizBeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:44:58