2012-04-27 15 views
0

我試圖創建一個響應式佈局,其中導航鏈接變成了某個屏幕大小的下拉菜單。我用下面的代碼中發現here如何在使用jQuery將無序列表菜單轉換爲下拉菜單時添加ID

$(function() { 
$('ul.selectdropdown').each(function() { 
    var $select = $('<select />'); 

    $(this).find('a').each(function() { 
     var $option = $('<option />'); 
     $option.attr('value', $(this).attr('href')).html($(this).html()); 
     $select.append($option); 
    }); 

    $(this).replaceWith($select); 
}); 
}); 

它的工作原理我想它的方式。但是,它不保留列表項最初具有的ID。我想要保留原始ID,或者爲每個創建的選項輸出一個唯一的ID。

有沒有簡單的方法來完成這個?

回答

1

您似乎沒有將ID分配給新創建的options。以下代碼假設<li>元素具有ID,而不是<a>

變化

$option.attr('value', $(this).attr('href')).html($(this).html()); 

$option.attr('value', $(this).attr('href')).html($(this).html()).attr('id', $(this).parent().attr('id')); 
+0

非常感謝您!這工作完美。 – sharcupine 2012-04-27 06:15:44