需求分析:
项目需求是做一个导航栏,点击不同的章节,显示相应的内容,同时高亮当前选择的章节。
最终效果:
以下是代码演示:
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
#menu{
width: 300px;
}
.has_children{
background: #69c;
color: #fff;
cursor: pointer;
}
.highlight{
color: #fff;
background: green;
}
ul{
list-style:none;
padding:0;
}
ul li{
background: #888;
display: none;
}
</style>
<script src="<%=path %>/js/jquery-1.4.1.js"></script>
<script type="text/javascript">
// $(function (){
// alert('第二章jQuery函数');
// });
$(function(){
$(".has_children").click(function(){
//为当前元素增加highlight类
$(this).addClass("highlight")
.children("li").show().end()
.siblings().removeClass("highlight")
.children("li").hide();
/*代码分析:
//这段代码的作用是:当鼠标点击到class中含有".has_children"的元素上的时候,给其添加一个名为"highlight"的class,然后将其内部li子元素都显示出来,并且被点击的".has_children"元素的同辈元素都去掉一个名为"highlight"的class,以及内部的li子元素统统隐藏。
//将子节点的li元素显示出来并重新定位到上次操作的元素
.children("li").show().end()
//获取元素的兄弟元素,并去掉他们的highlight类
.siblings().removeClass("highlight")
//将兄弟元素下的li元素隐藏
.children("li").hide();
*/
});
});
</script>
</head>
<body>
<div id="#menu">
<ul class="has_children">中国
<li>北京</li>
<li>上海</li>
<li>天津</li>
<li>重庆</li>
</ul>
<ul class="has_children">美国
<li>纽约</li>
<li>华盛顿</li>
<li>拉斯维加斯</li>
</ul>
<ul class="has_children">日本
<li>东京</li>
<li>名古屋</li>
<li>仙台</li>
</ul>
</div>
</body>
</html>