如何动态渲染 optgroup
时间: 2024-02-28 21:54:15 浏览: 134
动态渲染 optgroup 可以使用 JavaScript 或者 jQuery。以下是一个使用 jQuery 动态渲染 optgroup 的示例代码:
```html
<select id="mySelect"></select>
```
```javascript
var options = [
{ value: '1', text: 'Option 1', group: 'Group 1' },
{ value: '2', text: 'Option 2', group: 'Group 1' },
{ value: '3', text: 'Option 3', group: 'Group 2' },
{ value: '4', text: 'Option 4', group: 'Group 2' },
];
// Create a dictionary to hold the groups
var groups = {};
// Loop through the options and group them by group name
for (var i = 0; i < options.length; i++) {
var option = options[i];
var groupName = option.group;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(option);
}
// Loop through the groups and add them to the select
for (var groupName in groups) {
var groupOptions = groups[groupName];
var $optgroup = $('<optgroup label="' + groupName + '"></optgroup>');
for (var j = 0; j < groupOptions.length; j++) {
var option = groupOptions[j];
$optgroup.append('<option value="' + option.value + '">' + option.text + '</option>');
}
$('#mySelect').append($optgroup);
}
```
这段代码会将 options 数组中的选项动态渲染为带有 optgroup 分组的 select 元素。
阅读全文
相关推荐


















