Javascript 如何使用jquery在点击li时获取列表项的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3811313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:14:37  来源:igfitidea点击:

How to get the index of list Items on click of li using jquery

javascriptjqueryhtml-lists

提问by Bin2k

Is there a way through which I can get the index of list Items on click of lielement using JavaScript/jQuery?

有没有办法通过li使用 JavaScript/jQuery单击元素来获取列表项的索引?

<ul>
  <li>item1</li>
  <li>item2</li>
  <li>item3</li>
</ul>

回答by Thomas Clayson

$('ul li').click(function(){ alert($(this).index()); });

回答by Thariama

Use the onClick event to call the function getIndex (no jQuery needed, just vanilla javascript):

使用 onClick 事件调用函数 getIndex(不需要 jQuery,只需要普通的 javascript):

onClick = "getIndex(this);"

function getIndex(node) {
  var childs = node.parentNode.childNodes;
  for (i = 0; i < childs.length; i++) {
    if (node == childs[i]) break;
  }
  return i;
}

Index will start beginning with 0! To let it start with 1 : return i+1

索引将从 0 开始!让它从 1 开始:return i+1