jQuery EasyUI 表单 – 格式化下拉框(ComboBox)
jQuery EasyUI 中的 combobox(下拉框)支持自定义下拉面板中每一项的显示格式。通过 formatter 函数,可以返回 HTML 字符串来格式化每个选项(如添加图片、颜色、图标、多字段显示等)。这非常适合需要富文本显示的场景,比如带图标的选项或复合文本。
1. 基本用法
- 在初始化 combobox 时添加
formatter属性。 formatter函数接收一个参数row(当前数据行对象),返回 HTML 字符串。
示例 HTML:
<input id="cc" class="easyui-combobox" style="width:300px;"
data-options="valueField:'id',textField:'text',url:'combobox_data.json'" />
JavaScript 初始化(带格式化):
$('#cc').combobox({
url: 'combobox_data.json',
valueField: 'id',
textField: 'text',
formatter: function(row) {
// 简单示例:加粗文本
return '<strong>' + row.text + '</strong>';
}
});
2. 常见格式化示例:带图片的选项
官方经典示例:在下拉项中显示图片 + 文本。
数据格式(combobox_data.json):
[{
"id": 1,
"text": "Java",
"icon": "java.png"
}, {
"id": 2,
"text": "JavaScript",
"icon": "js.png"
}]
格式化代码:
$('#cc').combobox({
url: 'combobox_data.json',
valueField: 'id',
textField: 'text',
panelHeight: 'auto', // 自动高度
formatter: function(row) {
var img = 'images/' + row.icon; // 图片路径
return '<img class="item-img" src="' + img + '" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>' +
'<span class="item-text">' + row.text + '</span>';
}
});
CSS 样式(可选美化):
.item-img {
float: left;
}
.item-text {
margin-left: 28px;
line-height: 20px;
}
效果:下拉面板中每项左侧显示小图标,右侧显示文本。
3. 其他格式化示例
- 多字段显示(如姓名 + 部门):
formatter: function(row) {
return row.name + ' (' + row.dept + ')';
}
- 带颜色标签:
formatter: function(row) {
var color = row.status == 'active' ? 'green' : 'red';
return '<span style="color:' + color + '">' + row.text + '</span>';
}
- 多选模式下格式化(multiple: true):
格式化同样适用,下拉项会显示自定义 HTML。
4. 注意事项
formatter只影响下拉面板中的显示,不影响输入框的选中值(选中后输入框仍显示textField的值)。- 如果需要自定义输入框的显示文本,可以结合
onSelect事件手动设置:
onSelect: function(record) {
$(this).combobox('setText', record.name + ' - ' + record.code); // 自定义选中显示
}
- 对于更复杂的表格式下拉(如多列),推荐使用 combogrid(下拉数据网格),它支持列 formatter。
5. 在表单中使用
<form id="ff" method="post">
<div>
<label>语言:</label>
<input name="lang" class="easyui-combobox"
data-options="url:'combobox_data.json',valueField:'id',textField:'text',
formatter:formatItem, required:true" />
</div>
<div>
<input type="submit" value="提交" />
</div>
</form>
<script>
function formatItem(row) {
// 自定义格式化函数
return '<img src="images/' + row.icon + '" /> ' + row.text;
}
$('#ff').form('load', {lang: 1}); // 加载默认值
</script>
参考资源
- 官方教程:https://www.jeasyui.com/tutorial/form/form4.php
- 文档:https://www.jeasyui.com/documentation/combobox.php
- Demo 示例:https://www.jeasyui.com/demo/main/index.php?plugin=ComboBox
- 中文教程:https://www.runoob.com/jeasyui/jeasyui-form-form4.html
combobox 的 formatter 功能非常强大,能让下拉选项更直观美观。如果需要更高级的格式(如表格列),可以考虑 combogrid。有具体场景(如多列显示或自定义选中文本)可以再详细描述!