最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to find Nth Element , when a click is activated - Stack Overflow

matteradmin6PV0评论
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>

Is there any way to identify that when a mouse is clicked at random.

Is there anyway to get nth element of the selected through mouse ?

edit: when we click over a paragraph, i am using jquery

  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>

Is there any way to identify that when a mouse is clicked at random.

Is there anyway to get nth element of the selected through mouse ?

edit: when we click over a paragraph, i am using jquery

Share Improve this question edited Nov 25, 2012 at 10:29 John Dvorak 27.3k13 gold badges72 silver badges86 bronze badges asked Nov 25, 2012 at 10:16 user708537user708537 5
  • 1 what do you mean by selected through mouse? – Joseph Commented Nov 25, 2012 at 10:18
  • You mean, how to find the position of the element that was clicked? – John Dvorak Commented Nov 25, 2012 at 10:18
  • @JanDvorak yeah i am using jquery, yes when clicked through mouse – user708537 Commented Nov 25, 2012 at 10:25
  • 1 What is n in this case? How is the nth element related to the clicked element? – Felix Kling Commented Nov 25, 2012 at 10:41
  • possible duplicate of jQuery: best way to get the index of an element in an event handler – Felix Kling Commented Nov 25, 2012 at 19:03
Add a ment  | 

3 Answers 3

Reset to default 5

This logs the index of the paragraph that was clicked.

var $elems = $('p');
$elems.on('click', function(e) {
    var indexOfElem = $elems.index(this);
    console.log("Element with index: " + indexOfElem + " was clicked.");
});

Something like this?

The jQuery index function in jQuery returns the position of an element within the jQuery object. To find the position of the clicked element within some list:

var $elems = $("#context > p");
$elems.on("click", function() {
  var i = $elems.index(this);
  console.log(i); // use the index
});

try this :

    $('p').click(function () {

    alert($('p').index(this));
    });
Post a comment

comment list (0)

  1. No comments so far