如何在保留 addClass 和 removeClass 的同时简化我的 Jquery 代码?

问题描述 投票:0回答:0

每次添加新的 <li><img> 元素时,我还必须在 .js 文件中添加一行新代码

Codepen 这是在线代码,说明它如何工作以及在编辑脚本后应该如何继续工作。

//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");
  })

我希望能够通过保留 addClassremoveClassmouseentermouseleave 来简化我的代码,而不必在每次添加新元素时都添加另一行代码。

目前我只有这个来识别列表的元素:

  $(".list li").on('mouseenter', function() {
    var index = $(this).index()
  })
jquery mouseenter mouseleave
© www.soinside.com 2019 - 2024. All rights reserved.