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

如何在多个同class的Div中仅让被点击的Div触发JS效果

解决多个同类下拉按钮同时触发的问题

你的核心问题是全局选择器和全局变量导致操作了所有匹配元素,改成基于当前点击元素的局部查找就能解决,不用加一堆ID,修改后的代码如下:

修改后的JS代码

$(".examplebutton1").click(function() {
    // 缓存当前点击的按钮、对应的下拉内容和图标
    const $currentBtn = $(this);
    const $targetDropdown = $currentBtn.find(".exampledropdown");
    const $targetIcon = $currentBtn.find(".exampleboxheadercursoricon1");

    // 避免动画未完成时重复点击
    if ($targetDropdown.is(":animated")) return;

    // 只切换当前按钮下的下拉内容
    $targetDropdown.slideToggle(500);

    // 单独处理当前图标的旋转,用data属性存旋转状态
    const currentRotate = parseInt($targetIcon.data("rotate") || 0);
    const newRotate = (currentRotate + 180) % 360;
    $targetIcon.css("transform", `rotate(${newRotate}deg)`);
    $targetIcon.data("rotate", newRotate);
});

关键改动说明

  1. 替换全局选择器为局部查找:
    原代码里$(".exampledropdown")和document.querySelector(".exampleboxheadercursoricon1")会选中页面上所有匹配的元素,改成用$(this).find()只查找当前点击按钮内部的子元素,确保操作只作用于点击的那一组。

  2. 去掉全局状态变量:
    原全局的rotation1和transitionIsHappening1会让所有按钮共用同一个状态,现在用元素的data()方法存储每个图标的旋转角度,用:animated判断当前下拉是否在动画中,每个按钮独立管理自己的状态。

  3. 简化旋转逻辑:
    通过(currentRotate + 180) % 360自动处理旋转归零,不用额外判断是否等于360。

原HTML无需修改

你的HTML结构已经是父子层级关系,直接用上面的JS就能实现点击哪个按钮就展开哪个下拉的效果,不需要添加ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:20:36