1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style> 7 *{margin: 0;padding: 0;} 8 #tab{width: 410px;margin: 0 auto;} 9 #tit{overflow: hidden;} 10 #tit span{float: left;width: 100px;height: 30px;border: 1px solid red;text-align: center;line-height: 30px;font-size: 30px;} 11 #con{width: 406px;border: 1px solid red;list-style: none;height: 300px;} 12 #con li{width: 406px;height: 300px;text-align: center;line-height: 300px;font-size: 50px;color: red;display: none;} 13 #con .show{display: block;} 14 #tit .select{background: #ccc;} 15 </style> 16 </head> 17 <body> 18 <div id="tab"> 19 <div id="tit"> 20 <span class='select' >111</span> 21 <span >222</span> 22 <span >333</span> 23 <span >444</span> 24 </div> 25 <ul id="con"> 26 <li class="show" >内容1111</li> 27 <li>内容2222</li> 28 <li>内容3333</li> 29 <li>内容4444</li> 30 </ul> 31 </div> 32 33 <script> 34 var tit=document.getElementById('tit'); 35 var spans=tit.getElementsByTagName('span'); 36 var con=document.getElementById('con'); 37 var lis=con.getElementsByTagName('li'); 38 /*spans[0].abc=0; 39 spans[1].abc=1; 40 spans[2].abc=2; 41 spans[3].abc=3;*/ //给所有span扩充一个叫做abc的属性,abc的值就是span的下标值 42 for (var i = 0; i < spans.length; i++) { 43 //给所有span绑定一个点击事件,给所有的span一个index属性,index的值就是i也就是span的下标值 44 spans[i].index=i; 45 spans[i].onclick=function() { 46 for (var i = 0; i < spans.length; i++) { 47 spans[i].className=''; 48 lis[i].className=''; 49 };//清空所有的span以及li的类名 50 this.className='select'; 51 //当前点击的span类名为select 52 // console.log(this.index); 53 lis[this.index].className='show'; 54 //this.index指的是当前点击的span的下标值 55 56 }; 57 }; 58 </script> 59 </body> 60 </html>