gpt4 book ai didi

jquery - 将 UL 转换为带 OPTGROUP 的 SELECT

转载 作者:行者123 更新时间:2023-12-01 00:11:44 24 4
gpt4 key购买 nike

我正在尝试(使用 jQuery)将多级 UL 转换为 SELECT 下拉列表,其中嵌套的 UL 组被包装在 OPTGROUPS 中。我正在考虑使用这种技术来制作响应式网站菜单(想想下拉菜单)。

我过去曾将列表项转换为选项下拉列表,但从未使用 optgroups,而且我无法弄清楚。

我的 UL 结构示例;

<ul id="sitemap">
<li><a href="www.google.com">Home</a></li>
<li><a href="www.google.com">Small Business</a>
<ul>
<li><a href="www.google.com">Laptops</a></li>
<li><a href="www.google.com">Workstations</a></li>
<li><a href="www.google.com">Workstations</a></li>
<li><a href="www.google.com">Printers</a></li>
<li><a href="www.google.com">Mobile Phones</a></li>
</ul>
</li>
<li><a href="www.google.com">Public Sector</a>
<ul>
<li><a href="www.google.com">State Government</a></li>
<li><a href="www.google.com">Federal Government</a></li>
<li><a href="www.google.com">Support and Drivers</a></li>
</ul>
</li>
<li><a href="www.google.com">Large Enterprise</a>
<ul>
<li><a href="www.google.com">Services</a></li>
<li><a href="www.google.com">Solutions</a></li>
</ul>
</li>
</ul>

我将成为什么的示例;

<select id="sitemap">
<option href="www.google.com">Home</option>
<optgroup label="Small Business">
<option href="www.google.com">Laptops</option>
<option href="www.google.com">Workstations</option>
<option href="www.google.com">Printers</option>
<option href="www.google.com">Mobile Phones</option>
</optgroup>
<optgroup label="Public Sector">
<option href="www.google.com">State Government</option>
<option href="www.google.com">Federal Government</option>
<option href="www.google.com">Support and Drivers</option>
</optgroup>
<optgroup label="Large Enterprise">
<option href="www.google.com">Services</option>
<option href="www.google.com">Solutions</option>
</optgroup>
</select>

它不需要比一个级别更深 - 而且我很确定 optgroup 无论如何都不会真正工作得那么深。我们非常欢迎您提供任何帮助。谢谢。

最佳答案

一些简单的解决方案

var markUp = ["<select id='sitemap'>"], $li, $a;
$("#sitemap > li").each(function(){
$li = $(this);
if($li.find(">li").length){
markUp.push("<optgroup label='"+$li.find(">a").text()+"'>");
$li.find(">li").each(function(){
$a = $(this).find("a");
markUp.push("<option value='"+$a.attr("href")+"'>"+$a.text()+"</option>")
});
markUp.push("</optgroup>");
}
else{
$a = $li.find("a");
markUp.push("<option value='"+$a.attr("href")+"'>"+$a.text()+"</option>")
}
});
markUp.push("</select>");

$("#sitemap").replaceWith(markUp.join(''));
$("#sitemap").change(function(){ window.location = $(this).val(); });

关于jquery - 将 UL 转换为带 OPTGROUP 的 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6797684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com