為什么要document.getElementById("ul")[0]呢??不是只有一個(gè)<ul>標(biāo)簽嗎?奇怪的是去掉[0]之后獲取不到<ul>
<!DOCTYPE html>
<html>
<head>
? ? <meta charset="UTF-8">
? ? <title>實(shí)踐題 - 選項(xiàng)卡</title>
? ? <style type="text/css">
? ? ?/* CSS樣式制作 */??
? ? *{padding:0px;margin: 0px;font:12px normal "microsoft yahei";}
? ? #table{height:200px;width: 300px;}
? ? #table ul{border-bottom:2px solid brown;list-style: none;height: 30px;}
? ? #table ul li{cursor:pointer;float:left;list-style:none;height:28px;line-height:28px;margin:0px 3px;border:1px solid #aaaaaa;border-bottom:none;display:inline-block;width:60px;text-align: center;}
? ? #table ul li.active{border-top:2px solid brown;border-bottom: 2px solid #fff;}
? ? #table div{height:170px;line-height: 40px;border: 2px solid brown;border-top:none;}
? ? .hide{display:none;}
? ? </style>
? ? <script type="text/javascript">
? ? ? ? ?
? ? window.onload = function() {
? ? ? ? var table=document.getElementById("table");
? ? ? ? var ul=table.getElementsByTagName("ul")[0];
? ? ? ? var li=ul.getElementsByTagName("li");
? ? ? ? var div=table.getElementsByTagName("div");
? ? ? ? for(var i=0,len=li.length;i<len;i++)
? ? ? ? {
? ? ? ? ? li[i].index=i;
? ? ? ? ? li[i].onclick=function()
? ? ? ? ? {
? ? ? ? ? ? for(var j=0;j<len;j++)
? ? ? ? ? ? {
? ? ? ? ? ? ? li[j].className="";
? ? ? ? ? ? ? div[j].className="hide";
? ? ? ? ? ? }
? ? ? ? ? ? this.className="active";
? ? ? ? ? ? div[this.index].className="";
? ? ? ? ? }
? ? ? ? }
? ? }
? ??
? ??
? ? </script>
?
</head>
<body>
<!-- HTML頁(yè)面布局 -->
<div id="table">
? ? <ul>
? ? ? ? <li class="active">1</li><li>2</li><li>3</li>
? ? </ul>
</div>
?
</body>
</html>
2020-04-09
getElementsByTagName 的返回值是個(gè)數(shù)組,數(shù)組里面只有一個(gè)元素,訪問數(shù)組元素要用數(shù)組的下標(biāo),第一個(gè)元素的數(shù)組下表index 就是0