怎么用JS循环实现隐藏与显示ul
<div class="box_tit">
<a class="cur" href="javascript:void(0)">标题1</a>
<a href="javascript:void(0)">标题2</a>
<a href="javascript:void(0)">标题3</a>
</div>
<ul>
<li><a href="##">111111</a></li>
</ul>
<ul style="display:none;">
<li><a href="##">222222</a></li>
</ul>
<ul style="display:none;">
<li><a href="##">333333</a></li>
</ul>
</div>
<script>
var divs=document.getElementById("box");
var divv=divs.getElementsByTagName("div")[0];
var bt=divv.getElementsByTagName("a");
var uls=divs.getElementsByTagName("ul");
for(var i=0;i<3;i++){
bt[i].onclick=function(){
var uls=divs.getElementsByTagName("ul");
}
}
</script>
这里uls[i]是返回的是undefined,我想让这个循环让uls可以用要怎么办呢效果是想点击标题显示相应的ul,其他两个隐藏,用循环来做的,但是这个uls[i]拿不到,求援助
uls[i]能取值的话就可以写判断语句了,关键是这个uls[i]为什么不能用呢 展开
设置元素的display属性可以控制其显示与隐藏:block表示显示,none表示隐藏,关键代码:
obj.style.display = "block" ["none"];
实例演示——点击标题控制相应ul的显示和隐藏状态
1、HTML结构
<div id="test">
<a href="#" name="a1">title-1</a><a href="#" name="a2">title-2</a><a href="#" name="a3">title-3</a>
<ul id="ul_a1"><li>title-1-list-1</li><li>title-1-list-2</li><li>title-1-list-3</li></ul>
<ul id="ul_a2" style="display:none;"><li>title-2-list-1</li><li>title-2-list-2</li><li>title-2-list-3</li></ul>
<ul id="ul_a3" style="display:none;"><li>title-3-list-1</li><li>title-3-list-2</li><li>title-3-list-3</li></ul>
</div>
2、javascript代码
window.onload = function(){
var title = document.getElementById("test").getElementsByTagName("a");
var ul = document.getElementById("test").getElementsByTagName("ul");
for(i=0;i<title.length;i++){
title[i].onclick = function(){
for(j=0;j<ul.length;j++){
ul[j].style.display = "none";
}
document.getElementById("ul_"+this.name).style.display = "block";
}
}
}
3、效果演示
<div class="box" id="box">
<div class="box_tit">
<a class="cur" href="javascript:void(0)">标题1</a>
<a href="javascript:void(0)">标题2</a>
<a href="javascript:void(0)">标题3</a>
</div>
<ul>
<li><a href="##">111111</a></li>
</ul>
<ul style="display:none;">
<li><a href="##">222222</a></li>
</ul>
<ul style="display:none;">
<li><a href="##">333333</a></li>
</ul>
</div>
<script>
function dd(myObject) {
var s = "";
for (var property in myObject) {
s = s + "\n "+property +": " + myObject[property] +"<br>";
}
return s;
};
var divs=document.getElementById("box");
var divv=divs.getElementsByTagName("div")[0];
var bt=divv.getElementsByTagName("a");
var uls=divs.getElementsByTagName("ul");
for(var i=0;i<3;i++){
bt[i].onclick=function(){
var uls=divs.getElementsByTagName("ul");
alert(dd(uls));
}
}
</script>
没问题啊