如何在鼠标悬停事件时添加索引

how to add the index on mouse over event?

本文关键字:添加 索引 事件 悬停 鼠标      更新时间:2023-09-26

我有两个列表。我在鼠标悬停时获得列表项的索引.例如A有 0 个索引。B 有 1 个索引。但我想添加索引,换句话说,如果用户将鼠标悬停在第二个列表上A .it 给出的输出9而不是 0.。

我第一次在第二个名单上0..如果用户将鼠标悬停在第二个列表上,我希望它增加第一个列表的长度。

这是我的代码https://jsfiddle.net/e46atunm/1/

$(function() {
  $('#main-menu li').on({
    mouseenter: function() {
      console.log("mouse over: " + $(this).index())
    },
    mouseleave: function() {
      console.log("mouse leave: " + $(this).index())
    }
  });
})
index()使用

$(selector).index()只是索引兄弟姐妹的简单情况。

您还可以使用 $(collectionSelector).index(element) 在集合中建立索引:

var $li =  $('#main-menu li').on({
    mouseenter: function() {
      console.log("mouse over: " + $li.index(this))
    },
    mouseleave: function() {
      console.log("mouse leave: " + $li.index(this))
    }
  });

演示

我认为这可以工作

$(function() {
  $('#main-menu li').on({
    mouseenter: function() {
      var before = $(this).parents('section').prevAll().find('li').length;
      console.log("mouse over: ", before+$(this).index());
    },
    mouseleave: function() {
      var before = $(this).parents('section').prevAll().find('li').length;
      console.log("mouse leave: ", before+$(this).index());
    }
  });
})