在格言编号之后 - 将所有剩余的li项目包装成ul

时间:2014-07-25 12:22:12

标签: javascript jquery html-lists

我认为通过发布代码来理解我想要实现的目标要容易得多。但这个想法是。我有大约8个li项目,但是在3之后,我想创建一个名为“more”的新li项目,其余5个项目应该移动到一个新的ul,它将充当子菜单。 这是html

<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
</ul>

这是javascript

$('.ow_main_menu').each(function(){
    var max = 3
    if ($(this).find('li').length > max) {
        $(this).find('li:gt('+max+')').hide().end().append('<li class="show_more">More</li>');

        $('.show_more').hover( function(){
            /* stuck */
        });

    };
});

这就是它应该是什么样的

<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li class="show_more">More
        <ul>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </li>
</ul>

该节目更多部分我让它工作,但我不知道如何包装其余的项目。

2 个答案:

答案 0 :(得分:1)

以下是一种方法(虽然它仍然感觉有点过于笨重):

// using 'on()' to delegate the click-event handling to a 'ul' element
// that exists in the DOM, that becomes an ancestor to the created
// elements:
$('ul').on('click', 'li.more', function(e){
    $(this).find('ul').toggle();
});

// select all 'li' elements, retain only the 3rd (JavaScript's indexing is
// zero-based:
$('li').eq(2)
// get all the subsequent siblings:
.nextAll()
// wrap them all together within the supplied HTML:
.wrapAll('<li class="more">Read more<ul></ul></li>')
// find the ancestor 'ul' (to the 'li' elements returned by 'wrapAll()'):
.closest('ul')
// hide that 'ul':
.hide();

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

这是你可以做到的:

var max = 3;

$('ul').children('li:gt(' + (max - 1) + ')')     // find all LI after max
       .wrapAll('<ul>').parent()                 // wrap with UL and get it
       .wrap('<li class="show_more">More</li>'); // wrap UL with LI.show_more

演示:http://jsfiddle.net/n57g3/1/