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