JQuery - 如何将li移动到ul中的另一个位置? (交换2位的) [英] JQuery - How to move a li to another position in the ul? (exchange 2 li's)

查看:903
本文介绍了JQuery - 如何将li移动到ul中的另一个位置? (交换2位的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用这个什么是很酷的方法?我需要一个脚本来交换两个li>在 UL>。
它认为应该可以实现。感谢您的回复。

What is a cool way to apply this? I need a script that exchange two < li>'s position in an < ul>. It think that should be possible to achieve. Thanks for your response.

HTML

<div id="awesome">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>

伪JavaScript(JQuery)

Pseudo Javascript (JQuery)

$("#awesome ul li:eq(1)").exchangePostionWith("#awesome ul li:eq(3)");

HTML结果

<div id="awesome">
<ul>
<li>Item 1</li>
<li>Item 4</li>
<li>Item 3</li>
<li>Item 2</li>
<li>Item 5</li>
</ul>
</div>


推荐答案

您可以使用jQuery的。 after()用于移动元素。我克隆了其中的一个,所以原来可以保留为占位符。这就像是要转换变量 a b ,则需要一个第三个临时变量。

You can use jQuery's .after() for moving elements around. I cloned one of them so the original can remain as a placeholder. It's like if you wanted to switch variables a and b, you'd need a third temporary variable.

$.fn.exchangePositionWith = function(selector) {
    var other = $(selector);
    this.after(other.clone());
    other.after(this).remove();
};

现在你的伪代码 $(#awesome ul li:eq(1) ).exchangePositionWith(#awesome ul li:eq(3)); 不是这么伪: - )

Now your pseudocode $("#awesome ul li:eq(1)").exchangePositionWith("#awesome ul li:eq(3)"); isn't so pseudo :-)

这篇关于JQuery - 如何将li移动到ul中的另一个位置? (交换2位的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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