问题描述:

OnClicking on any <li><a>....</a></li> element except last child, this element should be moved to top as first child of <ul>.


FIDDLE


Description

By Default:

<ul>

<li><a href="#">01</a></li>

<li><a href="#">02</a></li>

<li><a href="#">03</a></li>

<li><a href="#">04</a></li>

<li><a href="#">05</a></li>

<li><a href="#">06 (Last Child)</a></li>

</ul>

If I click on 03, this list should become as below..

<ul>

<li><a href="#">03</a></li>

<li><a href="#">01</a></li>

<li><a href="#">02</a></li>

<li><a href="#">04</a></li>

<li><a href="#">05</a></li>

<li><a href="#">06 (Last Child)</a></li>

</ul>

But If Click on last child <li> this element should not be moved or changed... last child should remain as last always.

网友答案:

You can have a click event for li element except last element using $('li:not(:last)') element selector. and then use prependTo for appending as first child to parent:

$('li:not(:last)').click(function(){
 $(this).prependTo($(this).parent());
});

Working Demo

Update: Solution for targetting multiple UL elments

In case for multiple UL elements, you need to use :last-child instead of :last.As :last targets last element in matched set whereas :last-child will target all li that are last child.

网友答案:

You can use :not(:last) filter and jQuery prependTo:

$('li a:not(:last)').click(function() {

    $li = $(this).parent('li');

    $li.prependTo($li.parent('ul'));

    return false;
})
网友答案:

Check this updated JSFiddle

This works as per suggested. Just add the jquery to your code

相关阅读:
Top