我已經在SO上看到了更多然後幾個fewposts,它們正在尋找鏈接列表並將它們變爲下拉列表。我已經拿到了這些例子,並沒有太多的運氣將它們應用到我有點不同的標記上。我需要轉換一個帶標籤的單選按鈕的嵌套列表,並將它們轉換爲帶有<optgroup>
標題的下拉列表,去除嵌套的無線電輸入和標籤。jquery將單選按鈕的嵌套列表轉換爲具有optgroup標題的下拉列表
基本上單選按鈕Im的工作列表是一個瘋狂的失控和一個乾淨的下拉列表將更好的可用性和屏幕房地產。處理完轉換後,計劃將隱藏原始單選按鈕集,然後將用戶下拉選擇映射到相應的單選按鈕,以便在提交表單時進行處理。但首先我需要生成下拉列表。 。 。
這裏是起始標記的一個簡化的例子:
<ul>
<li>
<label><input type="radio">USA</label>
<ul class="children">
<li>
<label><input type="radio" >Northeast</label>
<ul class="children">
<li>
<label><input itype="radio">Mid-Atlantic</label>
</li>
<li>
<label><input type="radio">New England</label>
</li>
</ul>
</li>
<li>
<label><input type="radio">South</label>
</li>
<li>
<label><input type="radio">West</label>
</li>
</ul>
</li>
<li>
<label><input type="radio" checked="checked">No Venue Region</label>
</li>
</ul>
我試着去上述轉換爲以下幾點:
<select>
<optgroup label="USA">
<optgroup>Northeast</option>
<option>Mid-Atlantic</option>
<option>New England</option>
<optgroup>
<option>South</option>
<option>West</option>
</optgroup>
<option>No Region</option>
</select>
您可能會注意到頂層<ul>
在第一個例子,還有一個與它關聯的單選按鈕 - 但這是而不是,因爲我們希望用戶在選擇時儘可能精確。這些應該是標題,但不幸的是我無法控制產生的結果。
我喜歡的解決方案類型是使用函數來將現有標記處理爲新實體,然後我可以在隱藏原始後將其添加到父DOM元素。
在這SO thread @Enki提供了這種方法的解決方案,但我無法應用它,因爲我不能完全理解它是如何遍歷所有元素的。他的解決辦法是這樣的:
function sitemapCycle(){
if(typeof(sitemapNode)==="undefined") sitemapNode= $("#sitemap");
if($(this).find("ul").length)
{
sitemapNode= $(sitemapNode).append('<optgroup label="'+$(this).children().first().text()+'" />').children().last();
$(this).find("ul li").each(sitemapCycle);
sitemapNode= $(sitemapNode).parent();
}
else
{
$(sitemapNode).append('<option value="'+$(this).children().attr("href")+'">'+$(this).text()+'</option>');
}
}
var sitemapNode;
$("#sitemap").removeAttr("id").after('<select id="sitemap" />').children().each(sitemapCycle).parent().remove();
我已經能夠得到,不使用@恩基的做法最接近的,並且不產生OPTGROUP高層和is truly incomplete is this:
$(function() {
$('#venue-regionchecklist').each(function() {
$(this).find('label').each(function() {
var cnt = $(this).contents();
$(this).replaceWith(cnt);
});
var $select = $('<select />');
$(this).find('li').each(function() {
var $option = $('<option />');
$(this).html($(this).html());
$option.attr('id', $(this).attr('id')).html($(this).html());
$select.append($option);
});
$(this).replaceWith($select);
});
});
如果有人想採取a whack at it,這是一個簡略的收音機列表示例。我很想知道你會如何處理這類問題。
@Fabrico很抱歉,因爲長時間的延遲而表示感謝。這完全符合我的需求,並且您的評論思想讓我學習如何運作一切都非常有用。 – orionrush
@Fabrico也是'NBSPs(level)'功能,對於縮影來說是一個非常好的接觸! – orionrush
@ orionrush酷!我很高興它爲你工作。並且感謝所有這一次回來! :-) – Fabricio