jquery 下拉树
jQuery 下拉树实现方法
使用 jQuery 实现下拉树(树形下拉菜单)可以通过插件或自定义代码完成。以下是两种常见方法:
方法一:使用 jQuery 插件(如 jsTree)
-
引入必要的文件
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script> -
创建 HTML 结构
<div id="tree-container"></div> -
初始化 jsTree
$('#tree-container').jstree({ 'core' : { 'data' : [ { "text" : "Root node", "children" : [ { "text" : "Child node 1" }, { "text" : "Child node 2" } ]} ] } });
方法二:自定义 jQuery 树形下拉
-
创建 HTML 结构
<div class="tree-select"> <div class="selected-item">Select an item...</div> <ul class="tree-options"> <li> <span>Parent 1</span> <ul> <li>Child 1.1</li> <li>Child 1.2</li> </ul> </li> <li> <span>Parent 2</span> <ul> <li>Child 2.1</li> <li>Child 2.2</li> </ul> </li> </ul> </div> -
添加 CSS 样式
.tree-select { position: relative; width: 200px; } .tree-options { display: none; position: absolute; width: 100%; border: 1px solid #ccc; background: white; z-index: 1000; } .tree-options ul { padding-left: 20px; } .tree-options li { list-style: none; cursor: pointer; } -
添加 jQuery 交互
$(document).ready(function() { $('.selected-item').click(function() { $('.tree-options').toggle(); }); $('.tree-options li').click(function(e) { e.stopPropagation(); if ($(this).children('ul').length > 0) { $(this).children('ul').toggle(); } else { $('.selected-item').text($(this).text()); $('.tree-options').hide(); } }); $(document).click(function() { $('.tree-options').hide(); }); });
功能增强建议
-
添加搜索功能 可以通过添加输入框和过滤逻辑实现树节点的搜索功能。
-
多选支持 修改代码逻辑,允许选择多个节点并在 selected-item 区域显示已选项。
-
动态加载 对于大型树结构,可以实现节点的懒加载,当展开父节点时才加载子节点。

以上方法提供了基础实现,可根据具体需求进行调整和扩展。插件方式更适合复杂需求,自定义方式则更灵活轻量。






