Fancytree Javascript Tree的入门使用
一、概念----是做什么的能干什么
Fancytree是一个Javascript控件,它依赖于:
<script src="jquery.js"></script>
<script src="jquery-ui.min.js"></script>
<link href="ui.fancytree.min.css" rel="stylesheet" />
<script src="jquery.fancytree-all.min.js"></script>
具有以下几个亮点功能:
1) 支持Tree Table
2) checkbox选择框有三种状态,并可以disable掉checkbox选择框
3) 丰富的示例展示和代码展示、详尽的介绍文档、丰富的事件支持
4) 节点可编辑、拖拽、过滤、全选、统计子节点、延迟加载、皮肤设置、事件钩子支持、右键菜单、树内部可加入多种控件。
二、入门步骤
1)最简陋、基本的树
2)Fancytree所有配置项—名称、类型 的介绍
3)Fancytree的事件的大体使用介绍
4)Fancytree的属性、方法、参数的使用介绍
5)FancytreeNode 的属性、方法、参数的使用介绍
6)JS调取Fancytree、FancytreeNode对象和属性
7)Fancytree的事件钩子使用
备注:实用资料
1)
最简陋的树
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>fancyTreeTest</title>
<script src="jquery.js"></script>
<script src="jquery-ui.min.js"></script>
<link href="ui.fancytree.min.css" rel="stylesheet" />
<script src="jquery.fancytree-all.min.js"></script>
<script type="text/javascript">
$(function () {
//Create the tree inside the <div id="tree"> element.与zTree类似
// 基础配置,返回数据包括
$("#tree")
.fancytree({
source: [
{ "title": "Node 1", "key": "1" },
{
"title": "Folder 2",
"key": "2",
"folder": true,
"children": [
{ "title": "Node 2.1", "key": "3" },
{ "title": "Node 2.2", "key": "4" }
]
}
]
});
});
</script>
</head>
<body>
[...]
<!-- show tree -->
<div id="tree">...</div>
[...]
</body>
运行结果为
如果将以上的 body换为
<body>
[...]
<!-- show tree -->
<table id="tree">...</table>
[...]
</body>
运行结果为
最简单的树就完成了。
2)Fancytree所有配置项—名称、类型 的介绍。这些属性也就是说可以在
$("#tree").fancytree({
})之中添加的属性。
Name |
Type |
Description |
activeVisible |
Boolean |
Make sure that the active node is always visible, i.e. its parents are expanded (default: true). |
ajax |
object |
Default options for ajax requests |
aria |
Boolean |
(default: false) Add WAI-ARIA attributes to markup |
autoActivate |
Boolean |
Activate a node when focused with the keyboard (default: true) |
autoCollapse |
Boolean |
Automatically collapse all siblings, when a node is expanded (default: false). |
autoScroll |
Boolean |
Scroll node into visible area, when focused by keyboard (default: false). |
checkbox |
Boolean |
Display checkboxes to allow selection (default: false) |
clickFolderMode |
Integer |
Defines what happens, when the user click a folder node. |
1:activate, 2:expand, 3:activate and expand, 4:activate/dblclick expands (default: 4) |
||
debugLevel |
Integer |
0..2 (null: use global setting $.ui.fancytree.debugInfo) |
defaultKey |
function |
callback(node) is called for ner nodes without a key. Must return a new unique key. (default null: generates default keys like that: "_" + counter) |
enableAspx |
Boolean |
Accept passing ajax data in a property named `d` (default: true). |
extensions |
String[] |
List of active extensions (default: []) |
focusOnSelect |
Boolean |
Set focus when node is checked by a mouse click (default: false) |
generateIds |
Boolean |
Add `id="..."` to node markup (default: false). |
icons |
Boolean |
Display node icons (default: true) |
idPrefix |
String |
(default: "ft_") |
imagePath |
String |
Path to a folder containing icons (default: null, using 'skin/' subdirectory). |
keyboard |
Boolean |
Support keyboard navigation (default: true). |
keyPathSeparator |
String |
(default: "/") |
minExpandLevel |
Integer |
2: top-level nodes are not collapsible (default: 1) |
quicksearch |
Boolean |
navigate to next node by typing the first letters (default: false) |
scrollOfs: |
object |
optional margins for node.scrollIntoView() (default: {top: 0, bottom: 0}) |
scrollParent: |
jQuery |
scrollable container for node.scrollIntoView() (default: $container) |
selectMode |
Integer |
1:single, 2:multi, 3:multi-hier (default: 2) |
source |
any |
Used to Initialize the tree. |
strings |
object |
Translation table |
tabbable |
Boolean |
Add tabindex='0' to container, so tree can be reached using TAB |
titlesTabbable |
Boolean |
Add tabindex='0' to node title span, so it can receive keyboard focus |
toggleEffect |
object |
Animation options, false:off (default: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }) |
3)Fancytree的事件的大体使用介绍
<script>
$.ui.fancytree.debugLevel = 1; // silence debug output
function logEvent(event, data, msg) {
// var args = $.isArray(args) ? args.join(", ") :
msg = msg ? ": " + msg : "";
$.ui.fancytree.info("Event('" + event.type + "', node=" + data.node + ")" + msg);
} $(function () {
$("#tree")
.fancytree({
checkbox: true,
// --- Tree events -------------------------------------------------
blurTree: function (event, data) {
logEvent(event, data);
},
create: function (event, data) {
logEvent(event, data);
},
init: function (event, data, flag) {
logEvent(event, data, "flag=" + flag);
},
focusTree: function (event, data) {
logEvent(event, data);
},
restore: function (event, data) {
logEvent(event, data);
},
// --- Node events -------------------------------------------------
activate: function (event, data) {
logEvent(event, data);
var node = data.node;
// acces node attributes
$("#echoActive").text(node.title);
if (!$.isEmptyObject(node.data)) {
// alert("custom node data: " + JSON.stringify(node.data));
}
},
beforeActivate: function (event, data) {
logEvent(event, data, "current state=" + data.node.isActive());
// return false to prevent default behavior (i.e. activation)
// return false;
},
beforeExpand: function (event, data) {
logEvent(event, data, "current state=" + data.node.isExpanded());
// return false to prevent default behavior (i.e. expanding or collapsing)
// return false;
},
beforeSelect: function (event, data) {
// console.log("select", event.originalEvent);
logEvent(event, data, "current state=" + data.node.isSelected());
// return false to prevent default behavior (i.e. selecting or deselecting)
// if( data.node.isFolder() ){
// return false;
// }
},
blur: function (event, data) {
logEvent(event, data);
$("#echoFocused").text("-");
},
click: function (event, data) {
logEvent(event, data, ", targetType=" + data.targetType);
// return false to prevent default behavior (i.e. activation, ...)
//return false;
},
collapse: function (event, data) {
logEvent(event, data);
},
createNode: function (event, data) {
// Optionally tweak data.node.span or bind handlers here
logEvent(event, data);
},
dblclick: function (event, data) {
logEvent(event, data);
// data.node.toggleSelect();
},
deactivate: function (event, data) {
logEvent(event, data);
$("#echoActive").text("-");
},
expand: function (event, data) {
logEvent(event, data);
},
focus: function (event, data) {
logEvent(event, data);
$("#echoFocused").text(data.node.title);
},
keydown: function (event, data) {
logEvent(event, data);
switch (event.which) {
case 32: // [space]
data.node.toggleSelected();
return false;
}
},
keypress: function (event, data) {
// currently unused
logEvent(event, data);
},
lazyLoad: function (event, data) {
logEvent(event, data);
// return children or any other node source
data.result = { url: "ajax-sub2.json" };
// data.result = [
// {title: "A Lazy node", lazy: true},
// {title: "Another node", selected: true}
// ];
},
loadChildren: function (event, data) {
logEvent(event, data);
},
loadError: function (event, data) {
logEvent(event, data);
},
postProcess: function (event, data) {
logEvent(event, data);
// either modify the ajax response directly
data.response[0].title += " - hello from postProcess";
// or setup and return a new response object
// data.result = [{title: "set by postProcess"}];
},
removeNode: function (event, data) {
// Optionally release resources
logEvent(event, data);
},
renderNode: function (event, data) {
// Optionally tweak data.node.span
// $(data.node.span).text(">>" + data.node.title);
logEvent(event, data);
},
renderTitle: function (event, data) {
// NOTE: may be removed!
// When defined, must return a HTML string for the node title
logEvent(event, data);
// return "new title";
},
select: function (event, data) {
logEvent(event, data, "current state=" + data.node.isSelected());
var s = data.tree.getSelectedNodes().join(", ");
$("#echoSelected").text(s);
}
})
.bind("fancytreeactivate",
function (event, data) {
// alternative way to bind to 'activate' event
logEvent(event, data);
})
.on("mouseenter mouseleave",
".fancytree-title",
function (event) {
// Add a hover handler to all node titles (using event delegation)
var node = $.ui.fancytree.getNode(event);
node.info(event.type);
});
$("#btnSelect")
.click(function (event) {
var node = $("#tree").fancytree("getActiveNode");
node.setSelected(!node.isSelected());
});
$("#btnRemove")
.click(function (event) {
var node = $("#tree").fancytree("getActiveNode");
node.remove();
});
});
</script>
4)Fancytree的属性、方法、参数的使用介绍
Properties:
Type |
Name |
Description |
options |
||
rootNode |
||
activeNode |
||
focusNode |
||
jQueryObject |
$div |
|
object |
widget |
|
object |
ext |
|
object |
data |
|
object |
options |
|
string |
_id |
|
string |
statusClassPropName |
|
string |
ariaPropName |
|
string |
nodeContainerAttrName |
|
string |
$container |
|
lastSelectedNode |
Methods:
Return Type |
Name and Arguments |
Details |
FancytreeNode |
activateKey(key) Activate node with a given key and fire focus and activate events. A prevously activated node will be deactivated. If activeVisible option is set, all parents will be expanded as necessary. Pass key = false, to deactivate the current node only. |
|
$.Promise |
applyPatch(patchList) (experimental) |
|
void |
changeRefKey(oldRefKey, newRefKey) [ext-clones] Replace a refKey with a new one. |
|
void |
clearCookies() [ext-persist] Remove persistence cookies of the given type(s). Called like $("#tree").fancytree("getTree").clearCookies("active expanded focus selected"); |
|
void |
clearFilter() [ext-filter] Reset the filter. |
|
integer |
count() Return the number of nodes. |
|
void |
debug(msg) Write to browser console if debugLevel >= 2 (prepending tree name) |
|
integer |
filterBranches(filter, opts={autoExpand: false}) [ext-filter] Dimm or hide whole branches. |
|
integer |
filterNodes(filter, opts={autoExpand: false, leavesOnly: false}) [ext-filter] Dimm or hide nodes. |
|
FancytreeNode |
findNextNode(match, startNode) Find the next visible node that starts with `match`, starting at `startNode` and wrap-around at the end. |
|
void |
generateFormElements(selected=true, active=true, opts) Generate INPUT elements that can be submitted with html forms. In selectMode 3 only the topmost selected nodes are considered, unless `opts.stopOnParents: false` is passed. |
|
FancytreeNode |
getActiveNode() Return the currently active node or null. |
|
FancytreeNode | null |
getFirstChild() Return the first top level node if any (not the invisible root node). |
|
FancytreeNode |
getFocusNode() Return node that has keyboard focus or null. |
|
FancytreeNode | null |
getNodeByKey(key, searchRoot) Return node with a given key or null if not found. |
|
FancytreeNode[] | null |
getNodesByRef(refKey, rootNode) [ext-clones] Return all nodes with a given refKey (null if not found). |
|
void |
getPersistData() [ext-persist] Return persistence information from cookies Called like $("#tree").fancytree("getTree").getPersistData(); |
|
FancytreeNode |
getRootNode() Return the invisible system root node. |
|
FancytreeNode[] |
getSelectedNodes(stopOnParents=false) Return an array of selected nodes. |
|
boolean |
hasFocus() Return true if the tree control has keyboard focus |
|
void |
info(msg) Write to browser console if debugLevel >= 1 (prepending tree name) |
|
FancytreeNode | null |
isEditing() [ext-edit] Check if any node in this tree in edit mode. |
|
$.Promise |
loadKeyPath(keyPathList, callback) Make sure that a node with a given ID is loaded, by traversing - and loading - its parents. This method is ment for lazy hierarchies. A callback is executed for every node as we go. |
|
void |
reactivate() Re-fire beforeActivate and activate events. |
|
$.Promise |
reload(source) Reload tree from source and return a promise. |
|
void |
render(force=false, deep=false) Render tree (i.e. create DOM elements for all top-level nodes). |
|
void |
setFocus(flag=true) |
|
Array | object |
toDict(includeRoot=false, callback(node)) Return all nodes as nested list of NodeData. |
|
boolean |
visit(fn) Call fn(node) for all nodes. |
|
void |
warn(msg) Write warning to browser console (prepending tree info) |
5)FancytreeNode 的属性、方法、参数的使用介绍
new FancytreeNode(parent, obj)
Creates a new
FancytreeNode
Parameters:
Name |
Type |
Description |
parent |
||
obj |
Properties:
Type |
Name |
Description |
tree |
The tree instance |
|
parent |
The parent node |
|
string |
key |
Node id (must be unique inside the tree) |
string |
title |
Display name (may contain HTML) |
object |
data |
Contains all extra data that was passed on node |
FancytreeNode[] | null | undefined |
children |
Array of child nodes. |
boolean |
expanded |
Use isExpanded(), setExpanded() to access |
string |
extraClasses |
Addtional CSS classes, added to the node's |
boolean |
folder |
Folder nodes have different default icons and |
string |
statusNodeType |
null or type of temporarily generated system |
boolean |
lazy |
True if this node is loaded on demand, i.e. |
boolean |
selected |
Use isSelected(), setSelected() to access |
string |
tooltip |
Alternative description used as hover banner |
Methods:
Return |
Name and |
Details |
FancytreeNode |
addChildren(children, insertBefore) Append (or insert) a list of child nodes. |
|
FancytreeNode |
addNode(node, mode=child) Append or prepend a node, or append a child |
|
FancytreeNode |
appendSibling(node) Append new node after this. This a |
|
$.Promise |
applyPatch(patch) Modify existing child nodes. |
|
$.Promise |
collapseSiblings() Collapse all sibling nodes. |
|
FancytreeNode |
copyTo(node, mode=child, map) Copy this node as sibling or child of `node`. |
|
int |
countChildren(deep=true) Count direct and indirect children. |
|
void |
debug(msg) Write to browser console if debugLevel >= |
|
void |
discard() Deprecated. |
|
void |
editCreateNode(mode='child', init) [ext-edit] Create a new child or sibling node |
|
void |
editEnd(applyChanges=false) [ext-edit] Stop inline editing. |
|
void |
editStart() [ext-edit] Start inline editing of current |
|
FancytreeNode[] |
findAll(match) Find all nodes that contain `match` in the |
|
FancytreeNode |
findFirst(match) Find first node that contains `match` in the |
|
void |
fixSelection3AfterClick() Fix selection status, after this node was |
|
void |
fixSelection3FromEndNodes() Fix selection status for multi-hier mode. |
|
void |
fromDict(dict) Update node data. If dict contains |
|
FancytreeNode[] | undefined |
getChildren() Return the list of child nodes (undefined for |
|
FancytreeNode[] | null |
getCloneList(includeSelf=false) [ext-clones] Return a list of clone-nodes or |
|
FancytreeNode | null |
getFirstChild() Return the first child node or null. |
|
int |
getIndex() Return the 0-based child index. |
|
string |
getIndexHier() Return the hierarchical child index (1-based, |
|
string |
getKeyPath(excludeSelf=false) Return the parent keys separated by options.keyPathSeparator, |
|
FancytreeNode | null |
getLastChild() Return the last child of this node or null. |
|
int |
getLevel() Return node depth. 0: System root node, 1: |
|
FancytreeNode | null |
getNextSibling() Return the successor node (under the same |
|
FancytreeNode | null |
getParent() Return the parent node (null for the system |
|
FancytreeNode[] |
getParentList(includeRoot=false, includeSelf=false) Return an array of all parent nodes |
|
FancytreeNode | null |
getPrevSibling() Return the predecessor node (under the same |
|
boolean | undefined |
hasChildren() Return true if node has children. Return |
|
boolean |
hasFocus() Return true if node has keyboard focus. |
|
void |
info(msg) Write to browser console if debugLevel >= |
|
boolean |
isActive() Return true if node is active (see also |
|
boolean |
isChildOf(otherNode) Return true if node is a direct child of |
|
boolean |
isClone() [ext-clones] Return true if this node has at |
|
boolean |
isDescendantOf(otherNode) Return true, if node is a direct or indirect |
|
Boolean |
isEditing() [ext-edit] Check if this node is in edit |
|
boolean |
isExpanded() Return true if node is expanded. |
|
boolean |
isFirstSibling() Return true if node is the first node of its |
|
boolean |
isFolder() Return true if node is a folder, i.e. has the |
|
boolean |
isLastSibling() Return true if node is the last node of its |
|
boolean |
isLazy() Return true if node is lazy (even if data was |
|
boolean |
isLoaded() Return true if node is lazy and loaded. For |
|
boolean |
isLoading() Return true if children are currently beeing |
|
boolean |
isRootNode() Return true if this is the (invisible) system |
|
boolean |
isSelected() Return true if node is selected, i.e. has a |
|
boolean |
isStatusNode() Return true if this node is a temporarily |
|
boolean |
isTopLevel() Return true if this a top level node, i.e. a |
|
boolean |
isUndefined() Return true if node is lazy and not yet |
|
boolean |
isVisible() Return true if all parent nodes are expanded. |
|
void |
lazyLoad() Deprecated. |
|
$.Promise |
load(forceReload=false) Load all children of a lazy node if |
|
$.Promise |
makeVisible(opts) Expand all parents and optionally scroll into |
|
void |
moveTo(targetNode, mode, map) Move this node to targetNode. |
|
$.Promise |
navigate(where, activate=true) Set focus relative to this node and |
|
void |
remove() Remove this node (not allowed for system |
|
void |
removeChild(childNode) Remove childNode from list of direct |
|
void |
removeChildren() Remove all child nodes and descendents. This |
|
void |
render(force=false, deep=false) This method renders and updates all HTML · · · |
|
void |
renderStatus() Update element's CSS classes according to |
|
void |
renderTitle() Create HTML markup for the node's outer |
|
boolean |
reRegister(key, refKey) [ext-clones] Update key and/or refKey for an |
|
void |
resetLazy() Remove all children, collapse, and set the |
|
void |
scheduleAction(mode, ms) Schedule activity for delayed execution |
|
$.Promise |
scrollIntoView(effects=false, options=null) |
|
$.Promise |
setActive(flag=true, opts) Activate this node. |
|
$.Promise |
setExpanded(flag=true, opts) Expand or collapse this node. Promise is |
|
void |
setFocus(flag=true) Set keyboard focus to this node. |
|
void |
setSelected(flag=true) Select this node, i.e. check the checkbox. |
|
void |
setStatus(status, message, details) Mark a lazy node as 'error', 'loading', or |
|
void |
setTitle(title) Rename this node. |
|
void |
sortChildren(cmp, deep=false) Sort child list by title. |
|
NodeData |
toDict(recursive=false, callback) Convert node (or whole branch) into a plain |
|
void |
toggleExpanded() Flip expanded status. |
|
void |
toggleSelected() Flip selection status. |
|
boolean |
visit(fn, includeSelf=false) Call fn(node) for all child nodes. |
|
$.Promise |
visitAndLoad(fn, includeSelf=false) Call fn(node) for all child nodes and |
|
boolean |
visitParents(fn, includeSelf=false) Call fn(node) for all parent nodes, |
|
void |
warn(msg) Write warning to browser console (prepending |
6)JS调取Fancytree、FancytreeNode对象和属
//获取Id为tree的Fancytree对象
$("#tree").fancytree("getTree") //获取tree的根节点
$("#tree").fancytree("getRootNode") //访问每个节点并把节点展开
$("#tree").fancytree("getRootNode").visit(function(node) {
node.setExpanded(true);
})
备注:1)参考大牛:http://wwwendt.de/tech/fancytree/demo/
2)官方文档下载:http://wwwendt.de/tech/fancytree/demo/
Fancytree Javascript Tree的入门使用的更多相关文章
- Fancytree Javascript Tree TreeTable 树介绍和使用
Fancytree是一个非常棒的Javascript控件,功能强大,文档健全.在做Javascript Tree控件选型时,主要基于以下几点选择了Fancytree 在Javascript Tree控 ...
- JavaScript 10分钟入门
JavaScript 10分钟入门 随着公司内部技术分享(JS进阶)投票的失利,先译一篇不错的JS入门博文,方便不太了解JS的童鞋快速学习和掌握这门神奇的语言. 以下为译文,原文地址:http://w ...
- JavaScript面向对象轻松入门之封装(demo by ES5、ES6、TypeScript)
本章默认大家已经看过作者的前一篇文章 <JavaScript面向对象轻松入门之抽象> 为什么要封装? 封装(Encapsulation)就是把对象的内部属性和方法隐藏起来,外部代码访问该对 ...
- SharePoint Javascript客户端应用入门
SharePoint Javascript客户端应用入门 大家可以点击观看视频
- 华为云函数中使用云数据库的JavaScript SDK基础入门
背景介绍 使用云数据库Server端的SDK,此处我以华为提供的官方Demo为例,他们的Demo也已经开源放在了GitHub上,大家需要的可以自行下载. https://github.com/AppG ...
- javascript基础系列(入门前须知)
-----------------------小历史---------------------------- javascript与java是两种语言,他们的创作公司不同,JavaScript当时是借 ...
- JavaScript零基础入门
为什么学习JavaScript 1. 所有主流浏览器都支持JavaScript. 2. 目前,全世界大部分网页都使用JavaScript. 3. 它可以让网页呈现各种动态效果. 易学性 1.学习环境无 ...
- 【JavaScript】快速入门
摘抄地址快速入门 No1: JavaScript严格区分大小写 No2: JavaScript不区分整数和浮点数,统一用Number表示 NaN表示Not a Number,当无法计算结果时用NaN表 ...
- 【JavaScript】——JS入门
结束XML之旅,開始JavaScript的学习,看视频.了解了她的前世今生,还是为她捏了把汗啊! 看了部分视 频了,简单的总结一下吧! JavaScript是什么? JavaScript是一种基于面向 ...
随机推荐
- 【Android Developers Training】 12. 支持不同屏幕
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- JAVA基础——内部类详解
JAVA内部类详解 在我的另一篇java三大特性的封装中讲到java内部类的简单概要,这里将详细深入了解java内部类的使用和应用. 我们知道内部类可分为以下几种: 成员内部类 静态内部类 方法内部类 ...
- jq与原生js实现收起展开效果
jq与原生js实现收起展开效果 (jq需自己加载) <!DOCTYPE html> <html> <head> <meta charset="UTF ...
- java--while、do while、for三种循环体
1.for可以记录执行次数: 2.while.do while的i放在sum的后面和for得到的执行次数和结果是一致的. 1.从执行结果来看,放在前面,虽然执行次数和i放在sum的后面是相同,但是结果 ...
- OJ2236“孤单数”题目报告
题目描述:有2n+1个数,其中有n对数字是成双出现的,有且仅有1个数字只有它自己一个.请你找出这个孤单数. 输入描述: 第一行有且只有一个正整数n(n<=500000) 第二行有2n+1个数ai ...
- Spring事务管理的两种方式
参考文档: http://www.iteye.com/topic/1123347 http://blog.csdn.net/lcj8/article/details/2835432 PS:好像还是tx ...
- Win环境下Oracle小数据量数据库的物理备份
Win环境下Oracle小数据量数据库的物理备份 环境:Windows + Oracle 单实例 数据量:小于20G 重点:需要规划好备份的路径,建议备份文件和数据库文件分别存在不同的存储上. 1.开 ...
- java 对象与json互转
有时为了项目需求,会将对象数据转换成json数据,以下是个人根据项目需求实现的方法. 项目中需要将数据格式: [{ "node": "0", "ind ...
- Android创建窗口(一)创建应用窗口
所谓的窗口(Window)就是一个显示在手机屏幕上可视化视图的一片区域.在Android中窗口是一个抽象的概念,每一个Activity就对应着一个窗口,而所有的窗口都是由视图(View)来呈现,而我们 ...
- nyoj_471:好多的树(容斥原理)
题目链接: http://acm.nyist.net/JudgeOnline/problem.php?pid=471 还是直接上代码.. #include<bits/stdc++.h> u ...