如何获得点击元素的索引

How to get index of clicked element?

本文关键字:索引 元素 何获得      更新时间:2023-09-26

我的导航栏中有五个锚元素。我想用jQuery获取点击元素的索引。我试过这个代码。

$('.navigation ul li a').click(function(e) {
  e.preventDefault();
  var el = $(this).index();
  console.log(el);
 })

但是每次我在控制台得到0。

https://jsfiddle.net/2hg2fkda/提琴在这里

任何帮助将不胜感激。谢谢你,

try this:

$('.navigation ul li').click(function(e) {
  e.preventDefault();
  var el = $(this).index();
  console.log(el);
 })

索引可以被获取,如果它的列表。替换你的代码-

var el = $(this).parent().index();

https://jsfiddle.net/mailmerohit5/hg0dqnxb/

你可以试试这个:

$('.navigation ul li ').click(function (e) {
    alert($(this).index());
});
演示

你也可以试试这个!!

var el = $(this).closest('li').index();