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

两个span共用onclick的toggleClass函数时的互斥选中问题

实现互斥选中的解决方案

要实现单选互斥效果,只需修改select函数逻辑:先移除所有目标元素的active类,再给当前点击的元素添加该类。

修改后的JS代码:

function select(i) {
    const e = window.event;
    // 移除所有.selected元素的active类
    $('.selected').removeClass('active');
    // 给当前点击的元素添加active类
    $(i).addClass('active');
    e.stopPropagation();
}

如果需要支持点击已选中的元素取消选中的额外功能,可以增加判断逻辑:

function select(i) {
    const e = window.event;
    const isActive = $(i).hasClass('active');
    // 先移除所有active类
    $('.selected').removeClass('active');
    // 如果当前元素原本未激活,再添加active类
    if (!isActive) {
        $(i).addClass('active');
    }
    e.stopPropagation();
}

HTML部分保持不变即可:

<span class="selected" onclick="select(this);">text 1</span>
<span class="selected" onclick="select(this);">text 2</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:06:10