简体   繁体   English

使用 JavaScript 从列表中获取活动类索引

[英]Get the active class index from list using JavaScript

I want to get the active class index using JavaScript.我想使用 JavaScript 获取活动类索引。 i done it with jQuery but i need it with JavaScript.我是用 jQuery 完成的,但我需要用 JavaScript。

I done it with jQuery like this.我像这样用jQuery完成了它。

<li class="list"> .... </li>
<li class="list"> .... </li>
<li class="list"> .... </li>
<li class="list active"> .... </li>
<li class="list"> .... </li>

<script>
$('li.active').index()
</script>

i want same with javascipt我想和 javascipt 一样

You can use querySelectorAll() to select all the required elements.您可以使用querySelectorAll()来选择所有必需的元素。 Then convert it to array using javascript and then use indexOf() on that.然后使用 javascript 将其转换为数组,然后在其上使用indexOf()

 const list = [...document.querySelectorAll('.list')]; const active = document.querySelector('.list.active'); console.log(list.indexOf(active))
 <li class="list"> .... </li> <li class="list"> .... </li> <li class="list"> .... </li> <li class="list active"> .... </li> <li class="list"> .... </li>

You can use the .call() method to invoke the array type's native .indexOf() method.您可以使用.call()方法来调用数组类型的原生.indexOf()方法。 This is how the .index() method is implemented in jQuery if you look at the source code.如果您查看源代码,这就是.index()方法在jQuery实现方式。 more about the same 更多相同

 function getChildNumber(node) { return [].indexOf.call(node.parentNode.children, node); } let activeNode = document.getElementsByClassName('active')[0]; console.log(getChildNumber(activeNode));
 <li class="list"> .... </li> <li class="list"> .... </li> <li class="list"> .... </li> <li class="list active"> .... </li> <li class="list"> .... </li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM