概述
什么是 jsTree?
jsTree 是一个基于 jquery 的交互式树结构 js 插件。它是完全免费的,开源并在 MIT 许可证下分发。jsTree 易于扩展、定制主题和配置,支持 HTML 和 JSON 数据源以及 AJAX 加载。
jsTree 在任意一种 box-model (content-box 或 border-box) 下都能正常运行,也可以作为 AMD 模块加载。它具备一个用于响应式设计的内置移动端主题,并易于定制。jsTree 使用 jQuery 的事件系统,因此正如我们所熟悉的,树结构的回调绑定以及各类事件都是一样简单的。
下面是几个值得关注的功能:
- 支持拖放
- 快捷键
- 直接编辑、创建、删除
- 三态复选框
- 模糊搜索
- 自定义节点类型
快速开始 - 一切尽在眼前
1. 下载 jsTree 或使用 CDNJS
如果选择下载的方式,所有需要用到的文件都会在下载包的 dist/ 文件夹中。
2. 引入主题
虽然主题译者注:也称为插件皮肤是可以自动加载的,但考虑到性能因素,对这个 CSS 文件最好还是人工引入。
若代码托管在项目文件中:
<link rel="stylesheet" href="dist/themes/default/style.min.css" />
若使用 CDNJS:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
3. 设置容器
该容器元素就是你想放置你的树结构的位置,通常用一个 <div> 就够了。文末示例中仅包含一个嵌套的 <ul>,因为除此之外没有配置其他像 JSON 这样的数据源。
<div id="jstree_demo_div"></div>
4. 引入 jQuery
jsTree 要求 1.9.0 或更高版本 的 jQuery。你可以使用 CDN 版本的,也可以将 jQuery 下载到项目本地再引入。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
5. 引入 jsTree
对于将插件托管在项目本地的方式,生产环境下请使用插件的压缩版脚本:dist/jstree.min.js,而针对开发环境则可以使用 dist/jstree.js。
<script src="dist/jstree.min.js"></script>
使用 CDNJS 的方式:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
6. 创建实例
当 DOM 准备好后,就可以开始创建 jsTree 实例了。译者注:就是指前面那个 <div> 容器
$(function () { $('#jstree_demo_div').jstree(); });
7. 事件监听
当用户与结构树发生交互时,jsTree 通过事件来通知你产生了哪些改动。在本插件中绑定 jsTree 事件就和绑定一个 click 事件一样简单。在我们提供的 API 文档中,你可以查阅到完整事件列表的详情。
$('#jstree_demo_div').on("changed.jstree", function (e, data) {
console.log(data.selected);
});
8. 通过实例进行交互
一旦创建好实例,你就可以对它进行方法调用。在我们的 API 文档中,你可以找到完整的方法列表。下面例子中三种调用方式效果都是一样的:
$('button').on('click', function () {
$('#jstree').jstree(true).select_node('child_node_1');
$('#jstree').jstree('select_node', 'child_node_1');
$.jstree.reference('#jstree').select_node('child_node_1');
});
完整示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsTree test</title>
<!-- 2 load the theme CSS file -->
<link rel="stylesheet" href="dist/themes/default/style.min.css" />
</head>
<body>
<!-- 3 setup a container element -->
<div id="jstree">
<!-- in this example the tree is populated from inline HTML -->
<ul>
<li>Root node 1
<ul>
<li id="child_node_1">Child node 1</li>
<li>Child node 2</li>
</ul>
</li>
<li>Root node 2</li>
</ul>
</div>
<button>demo button</button>
<!-- 4 include the jQuery library -->
<script src="dist/libs/jquery.js"></script>
<!-- 5 include the minified jstree source -->
<script src="dist/jstree.min.js"></script>
<script>
$(function () {
// 6 create an instance when the DOM is ready
$('#jstree').jstree();
// 7 bind to events triggered on the tree
$('#jstree').on("changed.jstree", function (e, data) {
console.log(data.selected);
});
// 8 interact with the tree - either way is OK
$('button').on('click', function () {
$('#jstree').jstree(true).select_node('child_node_1');
$('#jstree').jstree('select_node', 'child_node_1');
$.jstree.reference('#jstree').select_node('child_node_1');
});
});
</script>
</body>
</html>