繁体   English   中英

使用 jquery 将所选 li 元素之后的所有元素移动到开头

[英]Move all elements after a selected li element to the start using jquery

是否可以使用 jquery 将选定的 li 元素之后的所有元素移动到开头? 例如,如果我从下面的 li 中选择 3。

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

结果

<ul>
<li>4</li>
<li>5</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

我是这样解决的:

$('li').click(function () {
    $(this).nextAll().prependTo('ul');
});

我不确定这是最好的解决方案,但它应该按预期工作

 // Set a click event listener $("ul").on( "click", "li", function() { // The first element in the ul list const first = $("ul li:eq(0)"); // The current element - the element you clicked on const current = $(this); // The current element's index (starts from 0) const currentIndex = current.index(); // Total amount of ul items const totalCount = $("ul li").length; // Loop from the current element position + 1 to the last one for (let i = currentIndex + 1; i < totalCount; i++) { const next = $("ul li:eq(" + i + ")"); // Insert the clone of next element before first one first.before(next.clone()); // Remove the original of the next element from the list next.remove(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM