面试题:获取大量数据中某一条的index
提问:
群里分享了一个面试题:页面里有很多条数据,怎么知道这条数据的index,并且不使用循环?
分析:
如果在数组里,直接用indexOf,但对于对象会比较麻烦。
在页面上,不使用循环的话,可以用定位来查询。
比如一个很整齐的列表:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getIndex</title>
<style>
ul {
position: relative;
}
li {
height: 40px;
line-height: 40px;
font-size: 30px;
text-indent: 1em;
border: 1px solid #666;
margin-bottom: -1px;
}
</style>
</head>
<body>
<ul id="ul">
li{$}*1000
</ul>
<script>
ul.onclick=function(e){
var t=e.target;
alert(t.offsetTop/(t.offsetHeight-1)); // -1 因为margin-bottom为-1
}
</script>
</body>
</html>
li那里用的emmet写法,每点击一次,即可弹出li对应的index值,前提是每个li都是一样的高度。
也可以扩展成一个整齐的表格,比如li的width给定,然后设置float:left,可以得到行数和列数,然后求出对应的index。

浙公网安备 33010602011771号