Home > Web Front-end > JS Tutorial > body text

JavaScript中获取元素索引的函数_javascript技巧

WBOY
Release: 2016-05-16 18:19:56
Original
1096 people have browsed it

 这是我在写结构/表现/行为完全分离的选项卡(jQ版和原生JS版)一文时发现的问题. 今天一个朋友也问到我这个问题, 这个函数的确很实用. 和大家分享一下我的实现方法.
代码:

复制代码 代码如下:

function index(current, obj){
for (var i = 0; i if (obj[i] == current) {
return i;
}
}
}

原理:
通过一个for循环遍历找出当前集合中与当前元素相等的元素,那么该元素的下标值即是当前元素在元素集合中的索引值.

优化下:
复制代码 代码如下:
 
function index(current, obj){
for (var i = 0, length = obj.length; iif (obj[i] == current) {
return i;
}
}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template