如何获得点击标签的位置?

Kaj*_*een 3 javascript jquery

我想得到点击元素位置的位置.如果我点击First p标签,警告框必须给出输出1.如果我点击一些文本p标签然后它应该给出输出3.我不知道如何做.请有人给我解决方案.提前致谢.

下面是我的HTML代码.

<div class="wrapper">
    <p>First</p>
    <p>Second</p>
    <p>Some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

下面是我的JQuery代码

<script src="jquery.js"></script>
<script>
   $('p').click(function() {
    alert("You clicked nth position tag");
   });
</script>
Run Code Online (Sandbox Code Playgroud)

Ale*_*har 5

你可以使用.index():

$('p').on('click', function() {
  //add 1 to get the desired result 
  //because index starts from 0 
  console.log($(this).index() + 1);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <p>First</p>
  <p>Second</p>
  <p>Some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

对于您的新要求,您可以使用.text():

$('p').on('click', function() {
  console.log(`You clicked ${$(this).index() + 1} nth position tag with text: ${$(this).text()}`);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <p>First</p>
  <p>Second</p>
  <p>Some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)

我使用了模板文字但你可以简单地使用字符串连接.