【发布时间】:2015-01-16 00:33:31
【问题描述】:
我有一个动态创建的导航,我无法为导航创建父/子列表。
我想根据可用空间在列表末尾添加一个名为“更多...”的链接。然后将所有剩余元素显示为 More...的子元素...
例如,如果我有元素 list1、list2、list3、..... list10。
它将显示为 list1、list2、list3、more... 其余链接将是 more... 的子链接。
我尝试为此创建一个脚本,我认为我非常接近。但我有以下两个问题:
- 如何在子列表周围添加 UL。
- 有时“更多...”会换到下一行。
以下是我的 JS 代码:
$(document).ready(function() {
var nav = $('ul');
var more = '<li><a href="#">More...</a></li>';
nav.prepend( more );
var availableSpace = nav.innerWidth();
var list = 0;
var countedSpace = 0;
$('li').each(function(){
var current = $(this);
countedSpace = countedSpace+current.outerWidth();
if (countedSpace < availableSpace) {
list++;
}
})
var showInList = list; //Space available for xx no. of items.
var newList = [];
// Start at 2, don't include dynamically added more link.
for (i = 2; i < showInList; i++) {
newList.push($(nav).find("li:nth-child("+i+")"));
}
newList.push(more);
var childList = [];
for (i = showInList; i <= nav.children().length; i++) {
childList.push($(nav).find("li:nth-child("+i+")"));
}
//nav.empty();
nav.html(newList);
$(nav).find("li:last-child").append(childList);
});
【问题讨论】:
标签: javascript jquery