我可以使用jQuery轻松地向上或向下移动li元素吗? [英] Can I use jQuery to easily shift li elements up or down?

查看:142
本文介绍了我可以使用jQuery轻松地向上或向下移动li元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的菜单:

    <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> 

有没有一种简单的方式,我可以使用jquery重新排序元素?我想像这样的事情:

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.

推荐答案

其实并没有那么难。 JQuery几乎可以通过insertBefore和insertAfter方法自动获取。

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);
}

您可以使用像
moveDown($('#menuAbout ));
和menuAbout项目将向下移动。

You could use these like moveDown($('#menuAbout')); and the menuAbout item would move down.

如果你想扩展jQuery以包含这些方法,你可以这样写:

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);
}

现在,您可以调用
$(# menuAbout)。moveDown();

and now you can call the functions like $("#menuAbout").moveDown();

这篇关于我可以使用jQuery轻松地向上或向下移动li元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆