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

使用jQuery移除选中项及实现点击仅对应Div添加active类

问题解答:jQuery 实现单个元素添加类与移除选中项

一、仅为点击按钮对应的 main__place 添加 active 类

原代码中点击按钮时选中了所有.main__place元素,导致全局添加类。解决核心是通过触发事件的按钮(this)精准定位对应容器:

修改后的点击事件代码:

$(".removeBtn").on("click",function(){
   // 仅给当前按钮的父容器添加active类
   $(this).parent(".main__place").addClass("active")
})

说明:$(this)指向当前点击的removeBtn按钮,.parent(".main__place")直接定位到该按钮所属的目标容器,避免选中所有同类型元素。

二、使用 jQuery 移除选中项

根据需求不同,有两种常见移除方式:

1. 移除整个 main__place 容器(含内部所有元素)

如果需要删除整个条目,可在添加类后调用.remove()方法,若配合CSS动画可增加延迟:

$(".removeBtn").on("click",function(){
   const $targetContainer = $(this).parent(".main__place")
   $targetContainer.addClass("active")
   // 延迟移除以配合动画(300ms为示例时长,可根据动画调整)
   setTimeout(() => {
     $targetContainer.remove()
   }, 300)
})

2. 仅移除内部的 place 元素

若仅需删除place模块而保留容器,可通过兄弟元素定位:

$(".removeBtn").on("click",function(){
   const $targetPlace = $(this).siblings(".place")
   $(this).parent(".main__place").addClass("active")
   setTimeout(() => {
     $targetPlace.remove()
   }, 300)
})

完整修正代码

HTML 部分

<div class="col-12">
    <div class="place" id="test-1"></div>
</div>
<div class="col-12">
    <div class="place" id="test-2"></div>
</div>
<div class="col-12">
    <div class="place" id="test-3"></div>
</div>

jQuery 部分

// 修正wrap方法的语法错误,正确生成class属性
$('.place').wrap('<div class="main__place"></div>')

// 插入移除按钮
$('<i class="fa fa-x removeBtn"></i>').insertBefore(".place")

// 点击事件:添加类并移除容器(示例方案)
$(".removeBtn").on("click",function(){
   const $container = $(this).parent(".main__place")
   $container.addClass("active")
   setTimeout(() => {
     $container.remove()
   }, 300)
})

注:原代码中wrap方法的参数写法有误(<div.class="main__place">),已修正为标准的class属性格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:10:50