請教下大神,為什么我第一次點標題的時候沒有反應(yīng)第二次就可以正常顯示或隱藏了
<!doctype html>
<html>
<head>
? ? <meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
? ? *{margin:0;
? ? ?padding:0;
? ? ?font-size:13px;
? ? ?list-style:none;}
.menu{width:210px;
? ? ? margin:50px auto;
? ? ? border:1px solid #ccc;}
.menu p{height:25px;
? ? ? ? line-height:25px;
? ? ? ? font-weight:bold;
? ? ? ? background:#eee;
? ? ? ? border-bottom:1px solid #ccc;
? ? ? ? cursor:pointer;
? ? ? ? padding-left:5px;}
.menu div ul{display:none;}
.menu li{height:24px;
? ? ? ? ?line-height:24px;
? ? ? ? ?padding-left:5px;}
</style>
<script type="text/javascript">
window.onload=function(){
? ? ? // 將所有點擊的標題和要顯示隱藏的列表取出來
? ? ? var uls=document.getElementById('menu').getElementsByTagName('ul');
? ? ? var ps= document.getElementById('menu').getElementsByTagName('p'); ??
? ? ?// 遍歷所有要點擊的標題且給它們添加索引及綁定事件
? ? ?if(uls.length!=ps.length)return;
? ? ? ? for (var i=0;i<uls.length;i++){
? ? ? ? ? ? ps[i].id=[i];
? ? ? ? ? ? ps[i].onclick=function(){
? ? ? ? ? ? ? if(uls[this.id].style.display=='none'){
? ? ? ? ? ? ? ?uls[this.id].style.display='block';?
? ? ? ? ? ? ? }
? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ?uls[this.id].style.display='none'; ?
? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ?// 獲取點擊的標題上的索引屬性,根據(jù)該索引找到對應(yīng)的列表
? ? ?// 判斷該列表,如果是顯示的則將其隱藏,如果是隱藏的則將其顯示出來
}
</script>
</head>
<body>
<div id="menu">
<div>
<p>Web前端</p>
<ul style="display:block">
<li>JavaScript</li>
<li>DIV+CSS</li>
<li>jQuery</li>
</ul>
</div>
<div>
<p>后臺腳本</p>
<ul>
<li>PHP</li>
<li>ASP.net</li>
<li>JSP</li>
</ul>
</div>
<div>
<p>前端框架</p>
<ul>
<li>Extjs</li>
<li>Esspress</li>
<li>YUI</li>
</ul>
</div>
</div>
</body>
</html>
2017-08-15
通過外鏈樣式和內(nèi)嵌樣式設(shè)置元素的display:none樣式,用js設(shè)置style.display=""并不起作用(通過行內(nèi)樣式設(shè)置的會起作用),此時走else給該元素添加了style=display:none;再次點擊時js設(shè)置樣式就起作用了。
2017-08-15
將ul的disply:none寫成行內(nèi)樣式就可以了,或者將if判斷語句那里的順序改一下,即當點擊的元素為顯示時將其隱藏,否則顯示
2017-08-09
window.onload=function(){
? ?var ps = document.getElementById('menu').getElementsByTagName('p');
? ?var uls = document.getElementById('menu').getElementsByTagName('ul');
? ?if (ps.length != uls.length) {
? ? ? ?return;
? ?}
? ?for (var i = 0; i < ps.length; i++) {
? ? ? ?ps[i].id = i;
? ? ? ?ps[i].onclick = function() {
? ? ? ? ? ?for (var j = 0; j < ps.length; j++) {
? ? ? ? ? ? ? ?uls[j].style.display = 'none';
? ? ? ? ? ?}
? ? ? ? ? ?uls[this.id].style.display='block';
? ? ? ?}
? ?}
}
我這樣可以