jquery将嵌套的单选按钮列表转换为带有optgroup标题的下拉列表

我已经在SO上看到了更多的post ,这些post正在寻找一个链接列表并将它们变成一个下拉列表。 我已经采用了这些例子,并没有太多的运气将它们应用到我的标记,这有点不同。 我需要使用标签打开带有标签的嵌套列表,并将它们转换为带有标题的下拉列表,删除嵌套的无线电输入和标签。

基本上我正在使用的单选按钮列表是一个非常失控,一个干净的下拉列表将是更好的可用性和屏幕空间。 处理完转换后,计划是隐藏原始单选按钮集,然后将用户下拉选项映射到相应的单选按钮,以便在提交表单时进行处理。 但首先我需要生成下拉列表。 。 。

以下是起始标记的简化示例:

 

我试图将上面的内容转换为以下内容:

   Northeast Mid-Atlantic New England  South West  No Region  

您可能会注意到第一个示例中的顶级

    也有一个与之关联的单选按钮 – 但这不是所希望的,因为我们希望用户在选择时尽可能精确。 这应该是标题,但不幸的是我无法控制生成的内容。

    我喜欢的解决方案类型是使用一个函数将现有标记处理成一个新实体,然后我可以在隐藏原始实体后附加到父DOM元素。

    在这个SO线程中 @Enki提供了这种方法的解决方案,但是我无法应用它,因为我无法理解它是如何迭代所有元素的。 他的解决方案是这样的:

     function sitemapCycle(){ if(typeof(sitemapNode)==="undefined") sitemapNode= $("#sitemap"); if($(this).find("ul").length) { sitemapNode= $(sitemapNode).append('').children().last(); $(this).find("ul li").each(sitemapCycle); sitemapNode= $(sitemapNode).parent(); } else { $(sitemapNode).append(''+$(this).text()+''); } } var sitemapNode; $("#sitemap").removeAttr("id").after('').children().each(sitemapCycle).parent().remove(); 

    我能够得到的最接近的,不使用@Enki的方法,并且不创建optgroup顶级水平并且真正不完整的是 :

     $(function() { $('#venue-regionchecklist').each(function() { $(this).find('label').each(function() { var cnt = $(this).contents(); $(this).replaceWith(cnt); }); var $select = $(''); $(this).find('li').each(function() { var $option = $(''); $(this).html($(this).html()); $option.attr('id', $(this).attr('id')).html($(this).html()); $select.append($option); }); $(this).replaceWith($select); }); }); 

    这是一个简单的无线电列表样本,如果有人想对它进行打击 。 我很想知道你将如何解决这类问题。

    队友的欢呼声!

    我相信递归可以在这里有所帮助:

     function buildDropDownFromUL(CurrentUL, level) { var dropDownHTML = ""; CurrentUL.children("li").each(function () { // Cycle through all LI elements if ($(this).children("ul").length == 0) { // There is no UL element in this LI so it means LI is a selectable option dropDownHTML = dropDownHTML + ""; } else { // There is a UL in the LI so it means the LABEL in the current LI is a OPTGROUP // and the UL should be again processed dropDownHTML = dropDownHTML + "" + "" + buildDropDownFromUL($(this).children("ul"), level + 1); } }); return dropDownHTML + ""; } 

    需要注意的是:该函数假定如果给定的LI元素仅包含LABEL元素(并且没有UL元素),那么LABEL是可选择的选项,如果LI包含LABEL和UL,那么LABEL是一个选项组。

    这就是小提琴

    我希望它有所帮助!