Javascript JQuery - 如何将 li 移动到 ul 中的另一个位置?(换2里的)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4612955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:16:52  来源:igfitidea点击:

JQuery - How to move a li to another position in the ul? (exchange 2 li's)

javascriptjquerydomhtml-lists

提问by Tomkay

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.

什么是应用它的酷方法?我需要一个脚本来交换 < ul> 中两个 < li> 的位置。它认为应该是可以实现的。感谢您的答复。

HTML

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>

Pseudo Javascript (JQuery)

伪 Javascript (JQuery)

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

HTML Result

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>

回答by David Tang

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 aand b, you'd need a third temporary variable.

您可以使用 jQuery.after()来移动元素。我克隆了其中一个,以便原始文件可以保留为占位符。就像如果你想切换变量ab,你需要第三个临时变量。

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

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

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

回答by Eligasht

 $("ul li a").click(function () {
    $(this).parent().insertBefore('ul li:eq(0)');
  });


<ul>
    <li><a>a</a></li>
    <li><a>b</a></li>
    <li><a>c</a></li>
    <li><a>d</a></li>
    <li><a>e</a></li>
    <li><a>f</a></li>
</ul>