Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

javascript - Can I use jQuery to easily shift li elements up or down?

I have a menu like this:

    <ul id="menu" class="undecorated"> 
        <li id="menuHome"><a href="/">Home</a> </li> 
        <li id="menuAbout"><a href="/Usergroup/About">About</a> </li> 
        <li id="menuArchives"><a href="/Usergroup/Archives">Archives</a> </li> 
        <li id="menuLinks"><a href="/Usergroup/Links">Links</a> </li> 
    </ul> 

Is there a simple way that I can use jquery to re-order elements? I'm imagining something like this:

$('#menuAbout').moveDown().moveDown()

But any other way of achieving this is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's actually not that hard. JQuery almost gets you there by itself with the insertBefore and insertAfter methods.

function moveUp($item) {
    $before = $item.prev();
    $item.insertBefore($before);
}

function moveDown($item) {
    $after = $item.next();
    $item.insertAfter($after);
}

You could use these like

moveDown($('#menuAbout'));

and the menuAbout item would move down.

If you wanted to extend jQuery to include these methods, you would write it like this:

$.fn.moveUp = function() {
    before = $(this).prev();
    $(this).insertBefore(before);
};

$.fn.moveDown = function() {
    after = $(this).next();
    $(this).insertAfter(after);
};

and now you can call the functions like

$("#menuAbout").moveDown();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...