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

如何简化jQuery代码:保留addClass/removeClass,新增元素无需加代码

问题描述

每次新增<li>和<img>元素时,都必须手动在JS文件中添加对应代码。现有实现代码如下:

//Mouseenter
$(".list li:nth-child(1)").on('mouseenter', function() {
  $(".img-display img.show").removeClass("show");
  $(".img-display img:nth-child(1)").addClass("show");
})

$(".list li:nth-child(2)").on('mouseenter', function() {
  $(".img-display img.show").removeClass("show");
  $(".img-display img:nth-child(2)").addClass("show");
})

$(".list li:nth-child(3)").on('mouseenter', function() {
  $(".img-display img.show").removeClass("show");
  $(".img-display img:nth-child(3)").addClass("show");
})

//Mouseleave
$(".list li:nth-child(1)").on('mouseleave', function() {
  $(".img-display img.show").addClass("show");
  $(".img-display img:nth-child(1)").removeClass("show");
})

$(".list li:nth-child(2)").on('mouseleave', function() {
  $(".img-display img.show").addClass("show");
  $(".img-display img:nth-child(2)").removeClass("show");
})

$(".list li:nth-child(3)").on('mouseleave', function() {
  $(".img-display img.show").addClass("show");
  $(".img-display img:nth-child(3)").removeClass("show");
})

需求:简化代码,必须保留addClass、removeClass、mouseenter和mouseleave方法,新增元素时无需添加新代码,已知可通过$(this).index()获取列表元素索引。


解决方案

直接给所有.list li绑定事件,利用索引关联对应的图片,代码如下:

// 绑定mouseenter事件
$(".list li").on('mouseenter', function() {
  const index = $(this).index();
  // 移除所有图片的show类
  $(".img-display img.show").removeClass("show");
  // 给对应索引的图片添加show类
  $(".img-display img").eq(index).addClass("show");
});

// 绑定mouseleave事件
$(".list li").on('mouseleave', function() {
  const index = $(this).index();
  // 移除对应索引图片的show类
  $(".img-display img").eq(index).removeClass("show");
  // 若需要恢复默认显示的图片(比如第一张),可添加以下代码
  // $(".img-display img").eq(0).addClass("show");
});

说明

  1. 直接绑定事件到所有.list li,新增元素只要符合选择器规则,就会自动继承事件,无需额外添加代码
  2. 通过$(this).index()获取当前悬停li的索引,再用.eq(index)定位到对应位置的图片
  3. 原mouseleave逻辑存在冗余操作($(".img-display img.show").addClass("show");无实际作用),已修正为直接移除对应图片的show类;若需要恢复默认显示的图片,可添加注释中的代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:05:27