代码如下
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Navigation Tree Example</title>
<style type="text/css">
A {text-decoration:none}
#productsmenu,#supportmenu,#contactmenu { display:none;margin-left:2em;}
</style>
</head>
<body>
<h1>Navigation Tree Example</h1>
<p>The navigation tree below alows you to expand and collapse items.</p>
<ul>
<li><a id="products" href="#">[+] Produts</a>
<ul id="productsmenu">
<li><a href="productlist.html">Product List</a></li>
<li><a href="order.html">Order Form</a></li>
<li><a href="pricelist.html">Price List</a></li>
</ul>
</li>
<li><a id="support" href="#">[+] Support</a>
<ul id="supportmenu">
<li><a href="support.html">Support Form</a></li>
<li><a href="contact.html">Contact Support</a></li>
</ul>
</li>
<li><a id="contact" href="#">[+] Contact Us</a>
<ul id="contactmenu">
<li><a href="service.html">Service Department</a></li>
<li><a href="sales.html">Sales Department</a></li>
</ul>
</li>
</ul>
<script type="text/javascript" src="Test.js"></script>
</body>
</html>
Test.js代码如下
function Toggle(e){
if(!e){
var e=window.event;
}
whichlink=(e.target)?e.target.id:e.secElement.id;
obj=document.getElementById(whichlink+"menu");
visible=obj.style.display=="block";
key=document.getElementById(whichlink);
keyname=key.firstChild.nodeValue.substring(3);
if(visible){
obj.style.display="none";
key.firstChild.nodeValue='[+] '+keyname;
}else
{
obj.style.display="block";
key.firstChild.nodeValue='[-] '+keyname;
}
}
document.getElementById('products').οnclick=Toggle;
document.getElementById('support').οnclick=Toggle;
document.getElementById('contact').οnclick=Toggle;
开始的时候一直报个错误,后来发现是Test.js引入那句话写在head里了,那是body还没加载,所以document.getElementById是得不到东西的。
把js引入那句话放到body的最后就好了。还有就是注意点击事件的substring的作用,是为了每次替换[+]和[-]。所以substring传参数是3。效果图如下