1

我使用此代码为我的下拉列表控件分组项目:

var item;

var GroupsGRP = jQuery('<optgroup/>', {
    label: 'Groups'
}).appendTo(selectControl);

var EmployeesGRP = jQuery('<optgroup/>', {
    label: 'Employees'
}).appendTo(selectControl);

jQuery('option', selectControl).each(function (i) {
    item = jQuery(this);

    if (item.attr("class") == 'Employees') {
        item.appendTo(EmployeesGRP);
    }
    else {
        item.appendTo(GroupsGRP);
    }

});

这个的输出是:

Employees
  Employee number one
  Employee number two
Groups
  Group number one
  Group number two

问题:

如果没有项目,我如何删除组标题?

4

1 回答 1

0

只需 wrapAll 使用您想要分组的类的选项,其余的将保持未分组:

假设你的 html 是:

<SELECT id="MainContent_DropDownList1">
    <option>Select One</option>
    <option class="Employees">Employee number one</option>
    <option class="Employees">Employee number two</option>
    <option class="Groups">Group number one</option>
    <option class="Groups">Group number two</option>
    <option>Not an employee or group</option>
</SELECT>

和jQuery:

$(function() {

    var EmployeesGRP = $('<optgroup/>');
    var GroupsGRP = $('<optgroup/>');

    EmployeesGRP .attr('label', 'Employees');
    GroupsGRP .attr('label', 'Groups');

    $('#MainContent_DropDownList1 .Employees').wrapAll(EmployeesGRP);
    $('#MainContent_DropDownList1 .Groups').wrapAll(GroupsGRP);

});

现场示例 - jsFiddle

于 2013-05-28T04:53:04.473 回答