据说这是一道笔试题,以下是代码,没什么要文字叙述的,就是点击哪个<li>弹出哪个<li>的索引值即可:
<html>
<head>
<style>
li{width:50px;height:30px;margin:5px;float:left;text-align: center;line-height: 30px;border-radius:4px;list-style-type: none;background: red;cursor:pointer;
}
</style>
<script>
window.οnlοad=function(){
//此处有三种方法
};
</script>
<head><body><div><ul><li>列表1</li><li>列表2</li><li>列表3</li><li>列表4</li><li>列表5</li></ul> </div></body>
</html>
第一种:
var oli=document.getElementsByTagName('li');for(var i=0; i<oli.length;i++){ oli[i].index=i;oli[i].οnclick=function(){alert('你点击的列表的下标是:'+this.index);//列表下标从0开始};}
除此之外还有别的方法:
var oli=document.getElementsByTagName('li');for(var i=0;i<oli.length;i++){oli[i].οnclick=(function(n){return function(){alert(n);}})(i)}
或者:var oli=document.getElementsByTagName('li');for(var i=0;i<oli.length;i++){(function(n){oli[i].οnclick=function(){alert(n);}})(i)}
效果:
点击“列表4”弹出: