javascript - 在选择菜单中添加 optgroup

标签 javascript jquery

我有一个 jQuery 代码,可以从 ul li menu 创建 select。我想从父菜单添加 optgroup,但不知道如何添加。这是我的代码:

// Create the dropdown base
jQuery("<select />").appendTo("#module-menu");

// Create default option "Go to..."
jQuery("<option />", {
    "selected": "selected",
    "value"   : "",
    "text"    : "Go to..."
}).appendTo("#module-menu select");

// Populate dropdown with menu items
jQuery("#menu a").each(function() {
    var el = jQuery(this);
    jQuery("<option />", {
        "value"   : el.attr("href"),
        "text"    : el.text()
 }).appendTo("#module-menu select");
});
jQuery("#module-menu select").change(function() {
    window.location = jQuery(this).find("option:selected").val();
});

最佳答案

$('#parent')
    .append($('<select>')
        .append($('<optgroup>')
            .prop('label', 'group 1')
            .append($('<option>')
                .text('option 1'))));​

Example here.

Another example taking data from ul.代码:

var sel = $('<select>');
$('#parent').append(sel);

$('#menu>li').each(function()
{
    var group = $('<optgroup>')
        .prop('label', $(this).find('>span').text());
    sel.append(group);

    $(this).find('ul>li').each(function()
    {
        var opt = $('<option>')
            .text($(this).find('>span').text());
        group.append(opt);
    });
});​

关于javascript - 在选择菜单中添加 optgroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12797241/

相关文章:

javascript - 列渲染,监听<i>标签的点击事件

javascript - typescript 访问修饰符

如果我将浏览器最小化得太小,jquery 移动表单输入字段会奇怪地调整大小

javascript - 2页之间实时同步

javascript - 第二页不适用于第一页中的代码

javascript - C3JS - 无法读取未定义的属性 'category10'

javascript - 如何调试使用 Testacular (Karma) 运行的 Jasmine 规范?

javascript - AngularJS 嵌套 ng-repeats 和嵌套绑定(bind)

jquery - 在 Safari 中的固定/静态未对齐元素之间滚动切换

javascript - 如何使用 jQuery 在没有其他元素的情况下切换一个元素?