关于jquery -- eq(0)的问题(列表)

在使用jQuery处理列表hover效果时遇到问题,通过mouseover和mouseout事件结合eq()选择器尝试为每个li绑定事件,但只对第一个li生效。错误代码为`$(this).eq(int).find(".List-tool")`。解决方案是将int替换为0,即`$(this).eq(0).find(".List-tool")`,修复了hover效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于jquery – eq(0)的问题(列表)

问题描述

最近做项目写前端的时候,发现在列表之中要给每一排加上单独的hover很麻烦,因为表格是使用thymeleaf的el表达式生成的
于是就想到了用 jquery 的 鼠标事件,并且使用了 eq(),给每个 li 绑定hover 事件,但出现了错误, 话不多说,看代码。

页面 li 生成

   <div class="song-txt">
     <li  th:each="songsListOne : ${songsListOne}" th:id="${songsListOne.songId}">
          <a th:id="${songsListOne.songId}" th:text="${songsListOne.songName}"></a>
          <span class="List-tool" style="display=none">
              <p class="add-toCollection" title="添加到收藏" th:id="${songsListOne.songId}"><img src="../images/添加到收藏.png"></p>
              <p class="add-toList" title="添加到列表" th:id="${songsListOne.songId}"><img src="../images/添加到列表.png"></p>
              <p class="play" title="播放" th:id="${songsListOne.songId}"><img src="../images/播放.png"></p>
          </span>
      </li>
   </div>

生成后的列表
在这里插入图片描述

我先用了这样的js去控制列表元素的hover ,这里使用了mouseover和mouseout,效果和hover是一样的。

 var int;
    $('.song-txt li').bind({
        'mouseover' : function(){
            int = $(this).index(); //获取当前元素的索引值
            $(this).eq(int).find(".List-tool").show();
        },
        'mouseout' : function(){
            $(this).eq(int).find(".List-tool").hide();
        }
    });

int 是去获取当前 li 的索引,所以 $(this).eq(int).find(".List-tool") 这句代码的意思就是
获取到 this,也就是 div中 的第 int个 li 当中的 span

但是,效果却如下,把鼠标放上去 ------动图有水印,请见谅

在这里插入图片描述

只有第一个li 发生了作用,其他的都在沉默…

 var int;
    $('.song-txt li').bind({
        'mouseover' : function(){
            int = $(this).index(); //获取当前元素的索引值
            $(this).eq(0).find(".List-tool").show();
        },
        'mouseout' : function(){
            $(this).eq(0).find(".List-tool").hide();
        }
    });

把eq(int) 中的int 换成0; 效果就出来了。

在这里插入图片描述

希望能够帮助到你。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值