<div class="box" id="tabFir"> <ul > <li class="selected">页卡一</li> <li>页卡二</li> <li>页卡三</li> </ul> <div class="selected">内容一</div> <div>内容二</div> <div>内容三</div> </div>
<script> window.onload = function(){ var tabFir = document.getElementById('tabFir'), oLis = tabFir.getElementsByTagName('li'), oDivs = tabFir.getElementsByTagName('div'); for (var i = 0; i < oLis.length; i++) { (function (num){ oLis[i].onclick = function(){ //形成了一个闭包 changeTab(num); } })(i); } function changeTab(n) { for (var i = 0; i < oLis.length; i++) { oLis[i].className = ""; oDivs[i].className = ""; } oLis[n].className = 'selected'; oDivs[n].className = 'selected'; } } </script>
这是最基本的一个选项卡的编写方式。第一步for循环为每个li 绑定了点击事件。这样做不太好。我们用事件委托的方法,把点击事件绑定在父级元素上。
<script> window.onload = function(){ var tabFir = document.getElementById('tabFir'), oLis = tabFir.getElementsByTagName('li'), oDivs = tabFir.getElementsByTagName('div'); for(var i=0;i<oLis.length;i++){ oLis[i].index = i; } //事件委托 tabFir.addEventListener('click',function(e){ //兼容性处理 var event = e ||window.event; var target = event.target || event.srcElement; //判断是否匹配目标元素 if(target.nodeName.toLocaleLowerCase() === 'li'){ var index = target.index; changeTab(index); } }); function changeTab(n) { for (var i = 0; i < oLis.length; i++) { oLis[i].className = ""; oDivs[i].className = ""; } oLis[n].className = 'selected'; oDivs[n].className = 'selected'; } } </script>