Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the eq() value?

Tags:

jquery

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);
});
like image 598
Ryan Avatar asked Jan 31 '11 10:01

Ryan


People also ask

What is EQ () method?

The eq() method is an inbuilt method in jQuery which is used to locate the selected elements directly and returns an element with specific index. Syntax: $(selector).eq(index) Parameters: Here the parameter “index” specifies the index of the element. Can either be positive or a negative number.

What is EQ in JS?

The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

What does has () do in jQuery?

The has() method returns all elements that have one or more elements inside of them, that matches the specified selector. Tip: To select elements that have multiple elements inside of them, use comma (see example below).

Which of the following CSS selectors will select the second div in jQuery?

myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).


1 Answers

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/

like image 69
jAndy Avatar answered Nov 15 '22 20:11

jAndy