使用jQuery将多级UL转换为带optgroup的selectbox

Convert multi-level UL to selectbox with optgroups using jQuery

本文关键字:optgroup selectbox 转换 jQuery 多级 UL 使用      更新时间:2023-09-26

我需要使用一个多级ul并创建一个带有optgroups的选择框。我想用jQuery来做这件事。optgroup标签将是任何孩子的父母。

我的标记:

<ul>
    <li><a href="#">Section 1</a> </li>
    <li><a href="#">Section 2</a>
        <ul>
            <li><a href="#">Section 2.1</a></li>
            <li><a href="#">Section 2.2</a></li>
            <li><a href="#">Section 2.3</a> </li>
        </ul>
    </li>
    <li><a href="#">Section 3</a></li>
</ul>

我需要什么:

<select>
<option value="#">Section 1</option>
<optgroup label="Section 2">
    <option value="#">Section 2.1</option>
    <option value="#">Section 2.3</option>
    <option value="#">Section 2.3</option>
</optgroup>
<option value="#">Section 3</option>
</select>

到目前为止,我可以创建一个选择框,但它只考虑一个级别:http://jsfiddle.net/RyanBrackett/0wp0ypng/

感谢的帮助

    // Create the dropdown base
$("<select />").appendTo(".mob-subpages");
var opt = "";
$(".wrapper").children('li').each(function(){
    if($(this).find('ul').length !== 0){
        opt += "<optgroup label="+"'"+$(this).children().html()+"'"+">";
        $(this).find('li').each(function(){
        opt += "<option>"+$(this).find('a').html()+"</option>";
         });
         opt += "</optgroup>";
    }else{
        opt += "<option>"+$(this).children().html()+"</option>";
    }
    console.log($(this).find('ul').length !== 0)

});
console.log(opt)
$(".mob-subpages select").append(opt)

更新的fiddle

此代码运行良好!!

检查并确认