programing

목록 요소 재정렬-jQuery?

luckcodes 2021. 1. 17. 11:30

목록 요소 재정렬-jQuery?


<li>JavaScript 또는 순수 jQuery로 요소 를 재정렬 할 수 있습니까? 따라서 다음과 같은 어리석은 목록이 있다면 :

<ul>
    <li>Foo</li>
    <li>Bar</li>
    <li>Cheese</li>
</ul>

목록 요소를 어떻게 이동합니까? 와 같이 목록 요소 Cheese앞에 목록 요소를 Foo넣거나 Foo뒤에 이동 합니다 Bar.

가능합니까? 그렇다면 어떻게?


var ul = $("ul");
var li = ul.children("li");

li.detach().sort();
ul.append(li);

이것은 <li>노드가 기본 순서로 정렬되는 간단한 예 입니다. li 노드와 관련된 데이터 / 이벤트를 제거하지 않기 위해 detach를 호출하고 있습니다.

정렬 할 함수를 전달하고 정렬을 수행하기 위해 사용자 지정 비교기를 사용할 수도 있습니다.

li.detach().sort(function(a, b) {
   // use whatever comparison you want between DOM nodes a and b
});

누군가가 요소를 위 / 아래로 이동하여 한 번에 한 단계 씩 목록을 이동하여 재정렬하려는 경우 ...

//element to move
var $el = $(selector);

//move element down one step
if ($el.not(':last-child'))
    $el.next().after($el);

//move element up one step
if ($el.not(':first-child'))
    $el.prev().before($el);

//move element to top
$el.parent().prepend($el);

//move element to end
$el.parent().append($el);

jQuery에서 제가 가장 좋아하는 것 중 하나는 아주 작은 부가 기능을 그렇게 빨리 작성하는 것이 얼마나 쉬운 지입니다.

여기에서는 선택기 배열을 사용하여 대상 요소의 자식을 정렬하는 데 사용하는 작은 추가 기능을 만들었습니다.

// Create the add-on

$.fn.orderChildren = function(order) {
	this.each(function() {
		var el = $(this);
		for(var i = order.length - 1; i >= 0; i--) {
			el.prepend(el.children(order[i]));
		}
	});
	return this;
};


// Call the add-on

$(".user").orderChildren([
	".phone",
	".email",
	".website",
	".name",
	".address"
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="user">
	<li class="name">Sandy</li>
	<li class="phone">(234) 567-7890</li>
	<li class="address">123 Hello World Street</li>
	<li class="email">someone@email.com</li>
	<li class="website">https://google.com</li>
</ul>
<ul class="user">
	<li class="name">Jon</li>
	<li class="phone">(574) 555-8777</li>
	<li class="address">123 Foobar Street</li>
	<li class="email">jon@email.com</li>
	<li class="website">https://apple.com</li>
</ul>
<ul class="user">
	<li class="name">Sarah</li>
	<li class="phone">(432) 555-5477</li>
	<li class="address">123 Javascript Street</li>
	<li class="email">sarah@email.com</li>
	<li class="website">https://microsoft.com</li>
</ul>

이 함수는 배열을 역방향으로 반복 .prepend하여 선택하지 않은 요소가 끝까지 푸시되도록 사용합니다.


다음은이 기능을 지원하는 jQuery 플러그인입니다. http://tinysort.sjeiti.com/


이 같은?

​var li = $('ul li').map(function(){
              return this;
         })​.get();
$('ul').html(li.sort());

데모

나는 당신이 이런 것을 원할 수도 있습니다.

$('ul#list li:first').appendTo('ul#list'); // make the first to be last...
$('ul#list li:first').after('ul#list li:eq(1)'); // make first as 2nd...
$('ul#list li:contains(Foo)').appendTo('ul#list'); // make the li that has Foo to be last...

여기 1여기 2 더


jquery ui 정렬 가능 살펴보기

http://jqueryui.com/demos/sortable/

ReferenceURL : https://stackoverflow.com/questions/3050830/reorder-list-elements-jquery