gpt4 book ai didi

javascript - 在选择菜单中添加 optgroup

转载 作者:行者123 更新时间:2023-11-29 10:49:44 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0