fancy
fancy

Reputation: 51393

How do I get the index of a list item during a click even on that item?

How do I get the index of a list item during a click even on that item?

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
<ul>

$('li').live('click', function(e){
    alert(e.index);
})

Thanks

Upvotes: 0

Views: 170

Answers (4)

Jasper
Jasper

Reputation: 76003

$(document).delegate('li', 'click', function () {
    alert($(this)).index());
});

Here is a demo: http://jsfiddle.net/xERTx/1/

.live() is now depreciated as of jQuery 1.7 in favor of .on() and .delegate() (source: http://api.jquery.com/live).

Upvotes: 3

Carls Jr.
Carls Jr.

Reputation: 3078

solution here

http://jsfiddle.net/SMpWs/1/

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

Upvotes: 0

Jim Jose
Jim Jose

Reputation: 1319

Try something like this,

$(e.target).index( $(e.target).parent() );

Upvotes: 0

griegs
griegs

Reputation: 22760

Have you tried the index keyword?

http://api.jquery.com/index/

Upvotes: 1

Related Questions