Ryan
Ryan

Reputation: 1791

How to get the eq() value?

Is this possible? For me to get the eq() value? For example, if I click the li:eq(2), var x will become 2. Here's the code.

$('#numbers ul li').click(function(){
  x=$(this).eq().val();
  alert(x);
});

Upvotes: 19

Views: 38137

Answers (5)

cnz018
cnz018

Reputation: 11

You must give a context to index() in order to have an equivalent of eq(). Otherwise index() returns a relative value.

 $('#numbers ul li').click(function(){
   var x=$(this).index('#numbers ul li');
   alert(x);
 });

Upvotes: 1

cArf
cArf

Reputation: 81

eq<> index:

scount=$(selector).length;
for(i=0; i<scount; i++){
    $("selector:eq("+i+")").attr("eq",i);
}
$("selector").click(function(){
    alert($(this).attr("eq"));
});

Upvotes: 3

Prabhagaran
Prabhagaran

Reputation: 3700

Try this one..

 $('#numbers ul li').click(function(){
   var x=$(this).index();
   alert(x);
 });

Upvotes: 1

Swanidhi
Swanidhi

Reputation: 2046

The answer above is wrong. Index provides a relative value with respect to its siblings. Hence, the value is expected to change.

It should be something like

$('.someClass').click(function(){
    var that_ = this;
    // your logic for this function
    ....
    ....
    var currentIndex = $('.someClass').index(_that);
});

Upvotes: 6

jAndy
jAndy

Reputation: 236092

The .index()what is this? method will do it.

$('#numbers ul li').click(function() {
  var self   = $(this),
      index  = self.index(),
      text   = self.text();

  alert(text + ' ' + index);
});

Demo: http://www.jsfiddle.net/Y2aDP/

Upvotes: 29

Related Questions