jQuery EasyUI 表单 – 创建树形下拉框(ComboTree)
jQuery EasyUI 中的 combotree(树形下拉框)是将下拉选择框(combo)和树控件(tree)结合的组件。它类似于 combobox,但下拉面板显示的是树形结构,非常适合展示层级数据(如部门、分类、地区等)。支持单选、多选(带复选框)、异步加载等功能。
1. 基本用法
- 使用
<input>或<select>元素,添加类easyui-combotree。 - 通过
data-options或 JavaScript 初始化。
示例 HTML(标记式创建):
<input id="cc" class="easyui-combotree" style="width:200px;"
data-options="url:'tree_data.json',required:true" />
JavaScript 创建:
$('#cc').combotree({
url: 'tree_data.json', // 数据源(远程或本地JSON)
required: true,
checkbox: false // 是否显示复选框(默认false,单选)
});
2. 数据格式
combotree 需要标准的树形 JSON 数据,节点格式:
[{
"id": 1,
"text": "节点1",
"state": "open", // open/closed
"children": [{
"id": 11,
"text": "子节点1"
}]
}]
本地数据示例:
$('#cc').combotree({
data: [{
id: 1,
text: '水果',
children: [{
id: 11,
text: '苹果'
}, {
id: 12,
text: '香蕉'
}]
}, {
id: 2,
text: '蔬菜'
}]
});
3. 多选模式(带复选框)
设置 multiple: true 和 checkbox: true 启用多选。
<input id="cc" class="easyui-combotree" style="width:300px;"
data-options="url:'tree_data.json',multiple:true" />
获取值:
- 单选:
$('#cc').combotree('getValue');// 返回选中节点 ID - 多选:
$('#cc').combotree('getValues');// 返回数组,如 [‘1′,’11’] - 获取文本:
$('#cc').combotree('getText');// 单选返回文本,多选返回逗号分隔文本
设置值:
$('#cc').combotree('setValue', '11'); // 单选
$('#cc').combotree('setValues', ['11','12']); // 多选
4. 常见属性
继承自 combo 和 tree,主要属性:
url:远程数据地址method:’get’ 或 ‘post’multiple:true/false 是否多选checkbox:true 显示复选框(多选时常用)onlyLeafCheck:true 只允许选中叶子节点cascadeCheck:true 级联选中(选中父节点时子节点自动选中)lines:true 显示连接线animate:true 动画效果onSelect:选中节点事件(单选)onCheck:复选框选中事件(多选)
示例:多选 + 级联
$('#cc').combotree({
url: 'tree_data.json',
multiple: true,
cascadeCheck: true,
onCheck: function(node, checked) {
console.log('选中节点:', node.id, checked);
}
});
5. 在表单中使用
结合 form 插件,combotree 可以作为表单字段提交。
<form id="ff" method="post">
<div>
<label>部门:</label>
<input name="dept" class="easyui-combotree"
data-options="url:'dept_tree.json',required:true" />
</div>
<div>
<input type="submit" value="提交" />
</div>
</form>
<script>
$('#ff').form({
onSubmit: function() {
return $(this).form('validate');
}
});
</script>
6. 高级用法
- 异步懒加载:在 tree 的
onBeforeExpand事件中动态加载子节点。 - 搜索过滤:EasyUI 原生不支持内置搜索,可扩展或结合第三方插件。
- 只显示叶子节点值:多选时常用
onlyLeafCheck: true。
参考资源
- 官方文档:https://www.jeasyui.com/documentation/combotree.php
- Demo 示例:https://www.jeasyui.com/demo/main/index.php?plugin=ComboTree
- 中文文档:https://www.jeasyui.cn/document/form/combotree.html
- 教程:https://www.runoob.com/jeasyui/jeasyui-form-form2.html
combotree 是处理层级选择的强大工具,结合表单验证和提交非常方便。如果需要多选、异步加载或其他自定义功能,可以进一步扩展。有具体需求(如多选显示优化或搜索)可以再详细问!