最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论
  <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));
    });
发布评论

评论列表(0)

  1. 暂无评论