admin管理员组

文章数量:1287942

I have five anchor elements in my navigation. I want to get index of clicked element with jQuery. I tried this code.

$('.navigation ul li a').click(function(e) {

  e.preventDefault();

  var el = $(this).index();
  console.log(el);

 })

But every time I get zero in console.

/ fiddle is here.

Any help will be appreciated. Thanks,

I have five anchor elements in my navigation. I want to get index of clicked element with jQuery. I tried this code.

$('.navigation ul li a').click(function(e) {

  e.preventDefault();

  var el = $(this).index();
  console.log(el);

 })

But every time I get zero in console.

https://jsfiddle/2hg2fkda/ fiddle is here.

Any help will be appreciated. Thanks,

Share Improve this question asked Sep 26, 2015 at 8:40 Nafees AnwarNafees Anwar 6,6083 gold badges27 silver badges44 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

try this:

$('.navigation ul li').click(function(e) {

  e.preventDefault();

  var el = $(this).index();
  console.log(el);

 })

Index can be fetched if its list . Replace your code here -

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

LIVE https://jsfiddle/mailmerohit5/hg0dqnxb/

you can try this one:

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

DEMO

you can also try this!!

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

Demo

本文标签: javascriptHow to get index of clicked elementStack Overflow