javascript和jquery分别实现树
来源:互联网 发布:李兴华讲的java怎么样 编辑:程序博客网 时间:2024/05/28 15:58
javascript tree,check的实现
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
- <mce:script language="javascript"><!--
- function nodeClick(o)
- {
- var obj, chk, disp, level, selectValue // 定义变量不说了吧
- obj = event.srcElement; // 将event的srcElement属性赋予obj,注:IE下。此属性和DOM的target属性兼容
- // srcElement是指发生事件的文档元素
- if (obj == o) // 如果obj与传过来的参数o相等,则返回
- return;
- // ----------------这一段的效果是将用户选择了哪几个checkbox显示出来
- // 如果元素是INPUT
- if (obj.tagName == "INPUT")
- {
- chk = obj.checked; // 将元素的checked值赋予chk,true or false
- // 取得input元素的父元素的样式的第2个字符,即下面的内联样式表中的id为tree,class为l1,l2,l3,l4的那些东西,取得值为1,2,3,4
- level = parseInt(obj.parentElement.className.substring(1));
- // 遍历input的父层所有相邻元素
- while (obj.parentElement.nextSibling && parseInt(obj.parentElement.nextSibling.className.substring(1)) > level)
- {
- obj = obj.parentElement.nextSibling.all.tags("INPUT")[0]; // 又通过父元素找父下面的input子元素
- obj.checked = chk; // 赋予值,true or false
- }
- // 作为最上端显示用,不过个人觉得直接用"selectedText"这样写不太严格
- selectedText.innerHTML = "U have selected: <b>" + getTreeValue() + " </b>"; // 调用了getTreeValue()方法,下有解释
- return;
- }
- // 如果元素不存在相邻节点了,则返回
- if (!obj.nextSibling)
- return;
- // ----------------这一段的效果是折叠树
- disp = obj.nextSibling.style.display != "none" ? "none" : "block"; // 如果相邻节点的style下的display属性不等于none,则
- // 将它(display)设为none,否则设为block
- level = parseInt(obj.className.substring(1));
- // 遍历obj的相邻节点
- while (obj.nextSibling && parseInt(obj.nextSibling.className.substring(1)) > level)
- {
- obj = obj.nextSibling;
- obj.style.display = disp; // 设display属性,显示或折叠起来
- }
- }
- // 此函数为取得已选择的节点,已选择的就把checkbox的值存入数组中
- function getTreeValue()
- {
- var val = [];
- var objs = document.getElementById("tree").all.tags("INPUT");
- for (var i = 0; i < objs.length; i++)
- if (objs[i].checked)
- val.push(objs[i].value);
- return val.join(",");
- }
- // --></mce:script>
- <mce:style><!--
- * {
- font-size: 9.5pt;
- }
- #tree div {
- height: 16px;
- background-repeat: no-repeat;
- padding-top: 2px;
- padding-left: 20px;
- cursor: default;
- }
- #tree .l1, .l2, .l3 {
- background-image: url('folder.gif');
- }
- #tree .l4 {
- background-image: url('file.png');
- }
- #tree .l1 {
- background-position: 2 0%;
- }
- #tree .l2 {
- background-position: 52 0%;
- }
- #tree .l3 {
- background-position: 64 0%;
- }
- #tree .l4 {
- background-position: 80 0%;
- }
- #tree input {
- margin: -2px;
- margin-right: 20px;
- }
- --></mce:style><style mce_bogus="1">
- * {
- font-size: 9.5pt;
- }
- #tree div {
- height: 16px;
- background-repeat: no-repeat;
- padding-top: 2px;
- padding-left: 20px;
- cursor: default;
- }
- #tree .l1, .l2, .l3 {
- background-image: url('folder.gif');
- }
- #tree .l4 {
- background-image: url('file.png');
- }
- #tree .l1 {
- background-position: 2 0%;
- }
- #tree .l2 {
- background-position: 52 0%;
- }
- #tree .l3 {
- background-position: 64 0%;
- }
- #tree .l4 {
- background-position: 80 0%;
- }
- #tree input {
- margin: -2px;
- margin-right: 20px;
- }
- </style>
- </head>
- <body>
- <div id="selectedText">
- </div>
- <div id="tree" style="width:300px;height:450px;border:1px outset #EEEEEE;padding-top:2px;overflow-x:hidden;overflow-y:scroll;display:inline" onmouseover="javascript:var obj=event.srcElement;if(obj!=this)obj.style.backgroundColor='#f3f6ff';" onmouseout="javascript:var obj=event.srcElement;if(obj!=this)obj.style.backgroundColor='';" onclick="javascript:nodeClick(this)">
- <div class="l1">
- 请选择部门
- </div>
- <div class="l2">
- <input type="checkbox" name="dept" value="申银万国">申银万国
- </div>
- <div class="l3">
- <input type="checkbox" name="dept" value="经纪管理总部">经纪管理总部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海余姚国债">上海余姚国债
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海新昌路证券营业部">上海新昌路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海莘庄证券营业部">上海莘庄证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海中华路证券营业部">上海中华路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海瞿溪路营业部">上海瞿溪路营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海东体育会路营业部">上海东体育会路营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海奉贤证券营业部">上海奉贤证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海福州路证券营业部">上海福州路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海余姚路证券营业部">上海余姚路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海虹古路证券营业部">上海虹古路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海龙茗路证券营业部">上海龙茗路证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海金山证券营业部">上海金山证券营业部
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="上海洛川东路营业部">上海洛川东路营业部
- </div>
- <div class="l3">
- <input type="checkbox" name="dept" value="银证通部门">银证通部门
- </div>
- <div class="l4">
- <input type="checkbox" name="dept" value="银证通结算机构">银证通结算机构
- </div>
- <div class="l3">
- <input type="checkbox" name="dept" value="经纪管理总部">经纪管理总部
- </div>
- </div>
- </body>
- </html>
JQUERY 实现无限极TREEVIEW
第一步:下载JQUERY和TREEVIEW插件。
JQUERY:http://jquery.bassistance.de/dist/jquery.js
TREEVIEW:http://jquery.bassistance.de/treeview/jquery.treeview.zip(注意:解压后里面的DEMO是不能正常显示的,因为缺少jquery.js。大家下载下来放到相应目录即可)
第二步:创建一个HTML文件
因为我们要利用一些图片资源,所以就在jquery.treeview.zip解压以后的目录里面创建。
例如我们创建一个treeview.html文件。用你喜欢的编辑器写以下的代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>TREEVIEW</title>
这里是引入jquery.js文件,我上面已经提过原来的压缩包是没有的,下载以后复制进去即可。
<script type="text/javascript" src="jquery.js"></script>
这里是引入treeview插件
<script type="text/javascript" src="jquery.treeview.js"></script>
下面这个是jquery的语法格式,不懂的可以到上面看我给的那些入门资料。
<script type="text/javascript">
$(function(){
$("ul").Treeview();
});
</script>
以下是一些CSS样式,这里是必须的。大家可以根据自己的喜好来改它的外观,这也是我特别欣赏 的地方
<style type="text/css">
.treeview, .treeview ul {
padding: 0;
margin: 0;
list-style: none;
}
.treeview li {
margin: 0;
padding: 4px 0 3px 20px;
}
.treeview li { background: url(images/tv-item.gif) 0 0 no-repeat; }
.treeview .collapsable { background-image: url(images/tv-collapsable.gif); }
.treeview .expandable { background-image: url(images/tv-expandable.gif); }
.treeview .last { background-image: url(images/tv-item-last.gif); }
.treeview .lastCollapsable { background-image: url(images/tv-collapsable-last.gif); }
.treeview .lastExpandable { background-image: url(images/tv-expandable-last.gif); }
</style>
</head>
<body>
大家可以根据自己的要求改下面的这些代码,只要结构按照html语言里的列表结构即可。
<ul> <li>Item 1 <ul> <li>Item 1.1</li> </ul> </li> <li class="closed">Item 2 (如果CLASS指定了closed,那么他默认是关闭的) <ul> <li>Item 2.1 <ul> <li>Item 2.1.1</li> <li>Item 2.1.2</li> </ul> </li> <li>Item 2.2</li> </ul> </li> <li>Item 3</li></ul>
</body>
</html>
jquery.treeview使用笔记
正好项目中用到了JQuery,所以就在网上找依赖JQuery的JS树,最终选择了jquery.treeview.js,原因之一,它是JQuery官方发布的JS库,另一方面,看了一下它的文档,使用起来也是很简单的。经过一个小时的研究,终于搞定,现把它的使用方法做个简要的说明,以做笔记。
要使用jquery.treeview.js,97xxoo当然第一步是要把它下载下来,放入自己的工程中,然后在页面文件中引进jquery.js,jquery.cookie.js,jquery.treeview.js,jquery.treeview.async.js四个库文件,其中最后一个是要使用异步加载结点的时候,要用到的,我的项目中已经用到了这个功能,在初始化树的时候,只加载顶层的数据,当点击顶层结点的时候,就去干才会去加载下一层的结点,所有的数据都是通过ajax去后台取得到数据。
将库文件引入后,下一步就是要定义一个列表UL:如这样:
<ul id="ProductTypes">
</ul>
树数据将会加载到这个UL里面
<script type="text/javascript">
$(document).ready(function(){
//alert('ready');
$("#ProductTypes").treeview({
url: "/FetchProductTypeServlet"
});
//alert('ready111');
});
</script>
这里面的意思就是当文档加载完成后,草榴社区向后台FetchProductTypeServlet获取数据,注意后台输出的数据必须是json格式的数据。
下一步就是后台FetchProductTypeServlet的数据输出部分了:
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=UTF-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
要将contenttype设置为"text/json",第一次加载初始数据的时候,会向这个FetchProductTypeServlet传递一个get参数:root=source,所以后台可以判断root参数是否是source,如果是source,则代表是第一次加载数据,如果不是source,则root参数传递的則是树结点的id.
数据格式如下:
[
{
"text": "1. Pre Lunch (120 min)",
"expanded": true,
"classes": "important",
"children":
[
{
"text": "1.1 The State of the Powerdome (30 min)"
},
{
"text": "1.2 The Future of jQuery (30 min)"
},
{
"text": "1.2 jQuery UI - A step to richnessy (60 min)"
}
]
},
{
"text": "2. Lunch (60 min)"
},
{
"text": "3. After Lunch (120+ min)",
"children":
[
{
"text": "3.1 jQuery Calendar Success Story (20 min)"
},
{
"text": "3.2 jQuery and Ruby Web Frameworks (20 min)"
},
{
"text": "3.3 Hey, I Can Do That! (20 min)"
},
{
"text": "3.4 Taconite and Form (20 min)"
},
{
"text": "3.5 Server-side JavaScript with jQuery and AOLserver (20 min)"
},
{
"text": "3.6 The Onion: How to add features without adding features (20 min)",
"id": "36",
"hasChildren": true
},
{
"text": "3.7 Visualizations with JavaScript and Canvas (20 min)"
},
{
"text": "3.8 ActiveDOM (20 min)"
},
{
"text": "3.8 Growing jQuery (20 min)"
}
]
}
]
格式说明:上面的1. Pre Lunch (120 min) 结点中:"expanded": true 代表这个结点下的child是展开的,children则是子结点的数据,节点3. After Lunch (120+ min)有8个子结点,其中子结点中有一个结点3.6 The Onion: How to add features without adding features (20 min),有一个id属性,同时hasChildren:true,表示其下面又有子结点,并且会向FetchProductTypeServlet传递参数为:root=id值,具体到这里就是root=36,那么点击这个结点的时候,后台就会接收到root=36这个值,然后我们就在具体应用中,通过数据库查询或者其它方式找到相对应的数据,然后将这些数据构造成treeview所需要的json数据,也即是上面所示格式的数据。
后台FetchProductTypeServlet代码如下:
public class FetchProductTypeServlet extends HttpServlet {
ProdTypeDao prodTypeDao = null;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
prodTypeDao = new ProdTypeDao();
super.init();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=UTF-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
PrintWriter out = response.getWriter();
String root = request.getParameter("root");
System.out.println("root:"+root);
try {
String output = generateNodeString(root);
System.out.println("output======"+output);
out.print(generateNodeString(root));
} catch (ActionException e) {
e.printStackTrace();
RequestDispatcher rd = null;
request.setAttribute("ActionException", e);
rd = request.getRequestDispatcher("/common/error.jsp");
rd.forward(request, response);
}
out.flush();
out.close();
}
private String generateNodeString(String id) throws ActionException {
if(id == null){
return "";
}else if(id.equalsIgnoreCase("source")){
return generateInitTreeString();
}else{
return generateTreeChildNodeString(Integer.parseInt(id));
}
}
private String generateTreeChildNodeString(int typeId) throws ActionException{
int typeId_ = typeId ;
Connection conn = null;
//hasSubItem
StringBuilder sb = new StringBuilder();
sb.append("[");
ArrayList<ProdTypeBean> l;
try {
l = prodTypeDao.fetchSubItem(typeId_);
} catch (ActionException e) {
e.printStackTrace();
throw new ActionException("generateTreeChildNodeString err","generateTreeChildNodeString","generateTreeChildNodeString err");
}
int i = 0;
for(Iterator it = l.iterator();it.hasNext();i++){
if(i>0){
sb.append(",");
}
ProdTypeBean item = (ProdTypeBean)it.next();
sb.append(generateNodeString(item));
}
sb.append("]");
return sb.toString();
}
private String generateLinkString(ProdTypeBean item){
return "<a href='../../CommendProduct?typeId="+item.getPT_ID()+"' target='main' >"+item.getPT_NAME()+"</a>";
}
private String generateNodeString(ProdTypeBean item){
StringBuilder sb = new StringBuilder();
sb.append(" {");
sb.append(" /"text/": /""+generateLinkString(item)+"/"");
try {
if(prodTypeDao.hasSubItem(item.getPT_ID())){
sb.append(", /"id/":/""+item.getPT_ID()+"/"");
sb.append(", /"hasChildren/":true");
}
} catch (ActionException e) {
e.printStackTrace();
return "{}";
}
sb.append(" }");
return sb.toString();
}
private String generateInitTreeString() throws ActionException{
int typeId_ = 0 ;
Connection conn = null;
//hasSubItem
StringBuilder sb = new StringBuilder();
sb.append("[");
ArrayList<ProdTypeBean> l;
try {
l = prodTypeDao.fetchSubItem(typeId_);
} catch (ActionException e) {
e.printStackTrace();
throw new ActionException("generateInitTreeString err","generateInitTreeString err","generateInitTreeString err");
}
int i = 0;
for(Iterator it = l.iterator();it.hasNext();i++){
if(i>0){
sb.append(",");
}
ProdTypeBean item = (ProdTypeBean)it.next();
sb.append(generateNodeString(item));
}
sb.append("]");
return sb.toString();
}
}
jQuery treeview在JSP中的应用
1. 配置,其中jquery.js和jquery.cookie.js要用jquery-treeview/ lib/下的
2. navigation.jsp
<%@ pagelanguage="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglibprefix="sql"uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglibprefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPEhtmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert title here</title>
<linkrel="stylesheet"href="css/jquery.treeview.css"/>
<linkrel="stylesheet"href="css/screen.css"/>
<scriptsrc="javascript/jquery.js"type="text/javascript"></script>
<scriptsrc="javascript/jquery.cookie.js"type="text/javascript"></script>
<scriptsrc="javascript/jquery.treeview.js"type="text/javascript"></script>
<scripttype="text/javascript">
$(document).ready(function(){
$("#navigation").treeview({
control:"#treecontrol",
persist: "location",
collapsed: true
});
});
</script>
</head>
<body>
<h1id="banner">
<a
href="http://bassistance.de/jquery-plugins/jquery-plugin-treeview/">jQuery
Treeview Plugin</a> Demo
</h1>
<divid="main">
<ahref=".">Main</a>
<h4>
Sample - navigation
</h4>
<divid="treecontrol">
<atitle="Collapse the entire tree below"href="#"><img
src="images/minus.gif"/> Collapse All</a>
<atitle="Expand the entire tree below"href="#"><img
src="images/plus.gif"/> Expand All</a>
<a
title="Toggle the tree below, opening closed branches, closing open branches"
href="#">Toggle All</a>
</div>
<ulid="navigation">
<c:forEachvar="list"items="${list}">
<li>
${list.item}
<c:iftest="${emptylist.itemsForItemId == false}">
<ul>
<c:forEachvar="list1"items="${list.itemsForItemId}">
<li>
${list1.item}
</li>
</c:forEach>
</ul>
</c:if>
</li>
</c:forEach>
</ul>
</div>
</body>
</html>
3. TestController
@Controller
publicclass TestController {
@Autowired
TestDao testDao;
@RequestMapping("/navigation.html")
public String navigation(HttpServletRequest request) {
request.setAttribute("list",testDao.findTopItem());
return"navigation";
}
@RequestMapping("/async.html")
public String async(HttpServletRequest request) {
return"async";
}
}
4. TestDaoImpl
@Repository("testDao")
publicclass TestDaoImplextends HibernateBaseDaoimplements TestDao {
@SuppressWarnings("unchecked")
public List<Item> findTopItem() {
return getHibernateTemplate().find("from Item where itemLevel = 1");
}
@SuppressWarnings("unchecked")
public List<Item> find(Long itemId) {
return getHibernateTemplate().find("from Item a where a.itemId = ?",
itemId);
}
@SuppressWarnings("unchecked")
public List<Item> findSubItem(Long itemId) {
List<Item> list = new ArrayList();
List<Item> itemList = find(itemId);
Set<Item> subList = itemList.get(0).getItemsForItemId();
for (Item item2 : subList) {
list.add(item2);
}
return list;
}
public Boolean hasSubItem(Long itemId) {
Boolean ret = false;
List<Item> subList = findSubItem(itemId);
if (!subList.isEmpty()) {
ret = true;
}
return ret;
}
}
- javascript和jquery分别实现树
- 下拉菜单分别用css,javascript,jquery实现
- 分别用javascript,jquery实现 对图片的放大镜效果
- JQuery和ASP.NET分别实现级联下拉框效果
- js和jquery分别实现tab标签页
- js和jquery分别实现对textarea字数…
- 使用js和jQuery分别实现弹起对象下标
- 通过jQuery和Bootstrap来分别实现轮播图
- 分别用C++和JavaScript 实现四则运算表达式求值
- 用css和JavaScript分别实现水平垂直居中
- 用JQuery和angularjs分别实现两个盒子间按钮的跳转(第三版 demo实现)
- 使用JavaScript和jQuery实现隔行变色
- JavaScript和jQuery实现定位导航功能
- JavaScript和JQuery实现必应搜索
- JavaScript和jQuery实现回到顶部效果
- 分别使用FlyJSONP和JQuery实现跨域的异步请求
- 分别使用FlyJSONP和JQuery实现跨域的异步请求
- 分别使用FlyJSONP和JQuery实现跨域的异步请求 .
- mount命令解释
- 奢望
- 经典面试题目
- FPGA_Embedded_9_13
- Rzpanel1的一个属性
- javascript和jquery分别实现树
- 图像处理之图像快速插值放缩算法
- 猜数字游戏
- nefu473最大流
- cocos2d
- CognosBI技术建议书
- AS3.0 效率优化
- Paxos算法学习笔记
- TCP/IP:认识TCP