You need to enable JavaScript to run this app. 使用JS实现点击<i>元素为对应关联<p>添加active类
优惠活动
大模型
产品
解决方案
定价
更多

使用JS实现点击<i>元素为对应关联<p>添加active类

修正后的交互实现

原代码的问题点

  • 拿到所有<p>标签后直接无差别加active类,完全没有把被点击的<i>和对应的<p>做关联,自然会导致所有p都被激活
  • 内部循环直接用未声明的i变量,和外层绑定事件的循环变量冲突,会引发遍历逻辑异常
  • 全程没有清除其他p上已经存在的active类,切换激活对象时旧的高亮状态会残留

实现思路

每次触发图标点击时按顺序执行:

  1. 先全量遍历所有<p>标签,统一移除每个元素上的active类,保证同一时间只有一个p处于激活状态
  2. 顺着被点击<i>的DOM结构向上找到和它同属一个块的父容器(也就是带first-1类的<li>节点)
  3. 从这个父容器内部找到对应的<p>元素,单独给它加上active类

完整可运行代码

修正后的JS逻辑

window.onload = function () {
    const infoIcons = document.querySelectorAll(".fa");
    // 为每个图标绑定点击事件
    for (let i = 0; i < infoIcons.length; i++) {
        infoIcons[i].addEventListener('click', handleIconClick);
    }

    function handleIconClick(e) {
        // 第一步:清除所有p标签上的active状态
        const allParagraphs = document.querySelectorAll("p");
        for (let idx = 0; idx < allParagraphs.length; idx++) {
            allParagraphs[idx].classList.remove("active");
        }

        // 第二步:定位当前点击图标对应的父级块
        const parentBlock = e.target.closest("li.first-1");
        // 第三步:给父块内的p标签加active类
        parentBlock.querySelector("p").classList.add("active");
    }
}

原有HTML结构无需修改

<div id="otherele" class="m-design">
    <li class="first-1">
        <h4>CHOOSE YOUR STYLE</h4> 
        <span class="info">
            <i class="fa fa-info-circle"></i>
        </span>
        <p>Select from full selection of Suites, Jackets, Shirts and much more to <br>get your best look</p>
    </li>
    <li class="first-1">
        <h4>CUSTOMIZE</h4> 
        <span class="info" id="text-update">
            <i class="fa fa-info-circle"></i>
        </span>
        <p>You may customize every detail of your garment and we will make exactly how you want it. You can customize Buttons, Monogram, Lining, Pant style etc.</p>
    </li>
</div>

这里用closest()方法查找父节点,不需要硬写多层parentElement的嵌套路径,哪怕后续DOM结构微调,只要<i>和对应<p>在同一个li.first-1容器内,逻辑就能正常运行,鲁棒性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 13:24:03