<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test</title>
<script>
window.onload=function() {
var lis = document.querySelectorAll('ul li')
for (var i = 0 i < lis.length i++) {
lis[i]._index = i
lis[i].onclick = function() {
alert(this._index + 1)
}
}
}
</script>
</head>
<body>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
</html>
方法二:闭包
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test</title>
<script>
window.onload = function ()
{
var lis = document.querySelectorAll ('ul li')
var anonymous = function (i)
{
lis[i].onclick = function ()
{
alert (i + 1)
}
}
for ( var i = 0 i < lis.length i++)
{
anonymous (i)
}
}
</script>
</head>
<body>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
</html>
方法三:使用 let 关键字 声明
浏览器及最低版本支持
Chrome Firefox (Gecko) Internet Explorer Opera
41.0 2.0 (1.8.1) [1] 11 17
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test</title>
<script>
window.onload = function ()
{
"use strict"
var lis = document.querySelectorAll ('ul li')
for ( var i = 0 i < lis.length i++)
{
let j = i
lis[i].onclick = function ()
{
alert (j + 1)
}
}
}
</script>
</head>
<body>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
</html>
还是很好用的就是获取元素所在索引,举一个例子比如做选项卡的时候
<a>1</a><a>2</a><a>3</a>这是3个菜单
底下有3个div
点击第几个a标签出现第几个div就可以用index了
$('a').click(function(){
var index=$('a').index(this)
$('div').eq(index),show()
})
数组哪里有字符串索引?var arr=[]
arr['a'] = 10//这样写是给arr对象添加一个叫a的属性,属性值是10,
你所谓的字符串索引就是arr对象的属性名?
for(var key in arr){
alert("key-value:"+key+"-"+arr[key])
}