요소를 전환하는 네이티브 jQuery 기능이 있습니까?
jQuery로 두 요소를 쉽게 바꿀 수 있습니까?
저는 가능하다면 한 줄로 이것을 하고 싶습니다.
선택 요소가 있고 옵션을 위 또는 아래로 이동할 수 있는 두 개의 버튼이 있으며 선택된 선택 항목과 대상 선택 항목이 이미 있습니다. if로 수행하지만 더 쉬운 방법이 있는지 궁금합니다.
다음은 jQuery만 사용하여 이 문제를 해결하는 흥미로운 방법입니다(두 요소가 서로 인접한 경우).
$("#element1").before($("#element2"));
또는
$("#element1").after($("#element2"));
파울로 말이 맞아요, 하지만 왜 그가 관련된 요소들을 복제하는지 모르겠어요.이 작업은 실제로 필요하지 않으며 요소 및 해당 하위 요소와 관련된 참조나 이벤트 수신기가 손실됩니다.
다음은 일반 DOM 메서드를 사용하는 비클론 버전입니다(jQuery에는 이 특정 작업을 더 쉽게 만드는 특별한 기능이 없기 때문에).
function swapNodes(a, b) {
var aparent = a.parentNode;
var asibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aparent.insertBefore(b, asibling);
}
없어요, 하지만 당신은 하나를 빠르게 만들 수 있어요.
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
용도:
$(selector1).swapWith(selector2);
선택기가 각각 1개의 요소와 일치하는 경우에만 작동하며, 그렇지 않으면 이상한 결과가 나타날 수 있습니다.
이 문제에 대한 많은 에지 사례가 있는데, 이는 수용된 답변이나 보빈스의 답변으로 처리되지 않습니다.복제와 관련된 다른 솔루션은 올바른 방향으로 가고 있지만 복제는 비용이 많이 들고 불필요합니다.우리는 복제를 하고 싶어합니다. 왜냐하면 두 변수를 어떻게 바꿀 것인가에 대한 오래된 문제 때문입니다. 단계 중 하나는 변수 중 하나를 임시 변수에 할당하는 것입니다.이 경우 할당(복제)은 필요하지 않습니다.jQuery 기반 솔루션은 다음과 같습니다.
function swap(a, b) {
a = $(a); b = $(b);
var tmp = $('<span>').hide();
a.before(tmp);
b.before(a);
tmp.replaceWith(b);
};
jQuery.before
세 데할 수 . - 요소를 로 만듭니다 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
$.fn.swapWith = function(that) {
var $this = this;
var $that = $(that);
// create temporary placeholder
var $temp = $("<div>");
// 3-step swap
$this.before($temp);
$that.before($this);
$temp.before($that).remove();
return $this;
}
디바를
temp
앞에this
이사를
this
앞에that
이사를
that
앞에temp
3b) 제거하기temp
그럼 이렇게 사용해주세요.
$(selectorA).swapWith(selectorB);
데모: https://jsfiddle.net/7t1hz94y/
두 개의 복제품이 필요하지 않습니다. 한 개면 됩니다.파올로 베르간티노의 답변을 들어보면 다음과 같습니다.
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
$(to).replaceWith(this);
$(this).replaceWith(copy_to);
});
};
더 빠를 겁니다.두 요소 중 더 작은 요소를 통과하는 것도 속도를 높일 것입니다.
전에 이런 기술을 사용한 적이 있습니다.http://mybackupbox.com 의 커넥터 목록에 사용합니다.
// clone element1 and put the clone before element2
$('element1').clone().before('element2').end();
// replace the original element1 with element2
// leaving the element1 clone in it's place
$('element1').replaceWith('element2');
선택한 여러 옵션을 위 또는 아래로 이동할 수 있는 기능을 만들었습니다.
$('#your_select_box').move_selected_options('down');
$('#your_select_boxt').move_selected_options('up');
종속성:
$.fn.reverse = [].reverse;
function swapWith() (Paolo Bergantino)
먼저 첫 번째/마지막으로 선택한 옵션이 위/아래로 이동할 수 있는지 확인합니다.그런 다음 모든 요소와 호출을 반복합니다.
swapWith(element.next() 또는 element.prev())
jQuery.fn.move_selected_options = function(up_or_down) {
if(up_or_down == 'up'){
var first_can_move_up = $("#" + this.attr('id') + ' option:selected:first').prev().size();
if(first_can_move_up){
$.each($("#" + this.attr('id') + ' option:selected'), function(index, option){
$(option).swapWith($(option).prev());
});
}
} else {
var last_can_move_down = $("#" + this.attr('id') + ' option:selected:last').next().size();
if(last_can_move_down){
$.each($("#" + this.attr('id') + ' option:selected').reverse(), function(index, option){
$(option).swapWith($(option).next());
});
}
}
return $(this);
}
복제하지 않은 다른 하나:
교환할 실제 요소와 공칭 요소가 있습니다.
$nominal.before('<div />')
$nb=$nominal.prev()
$nominal.insertAfter($actual)
$actual.insertAfter($nb)
$nb.remove()
그리고나서insert <div> before
그리고remove
나중에 당신이 확신할 수 없는 경우에만 필요합니다. (나의 경우에는) 항상 이전에 요소가 존재합니다.
이 솔루션은 상위 요소 내에서 여러 하위 요소를 위아래로 이동하는 방법입니다.목록 상자에서 선택한 옵션을 이동할 때 잘 작동합니다(<select multiple></select>
)
위로 이동:
$(parent).find("childrenSelector").each((idx, child) => {
$(child).insertBefore($(child).prev().not("childrenSelector"));
});
아래로 이동:
$($(parent).find("childrenSelector").get().reverse()).each((idx, child) => {
$(opt).insertAfter($(child).next().not("childrenSelector"));
});
jQuery 플러그인 "Swapable" 보기
http://code.google.com/p/jquery-swapable/
"Sortable"을 기반으로 하며 정렬 가능한 것처럼 보이지만(끌기-n-drop, 자리 표시자 등) 두 요소만 스왑합니다.다른 모든 요소는 영향을 받지 않으며 현재 위치를 유지합니다.
이것은 @lotif의 답변 논리에 기반한 답변이지만, 조금 더 일반화되었습니다.
요소를 실제로 이동한 후/전에 추가/전에 추가하는 경우
=> 복제가 필요하지 않음
=> 이벤트 보관
두 가지 경우가 발생할 수 있습니다.
- 하나의 목표물은 "ious"를 가지고 있습니다 => 우리는 다른 목표물을 그것을 넣을 수 있습니다.
- 하나의 대상은 그것의 첫 번째 아이입니다. => 우리는 다른 대상을 부모에게 줄 수 있습니다.
코드
이 코드는 더 짧게 만들 수 있지만, 가독성을 위해 이렇게 유지했습니다.부모(필요한 경우) 및 이전 요소를 사전에 저장해야 합니다.
$(function(){
var $one = $("#one");
var $two = $("#two");
var $onePrev = $one.prev();
if( $onePrev.length < 1 ) var $oneParent = $one.parent();
var $twoPrev = $two.prev();
if( $twoPrev.length < 1 ) var $twoParent = $two.parent();
if( $onePrev.length > 0 ) $onePrev.after( $two );
else $oneParent.prepend( $two );
if( $twoPrev.length > 0 ) $twoPrev.after( $one );
else $twoParent.prepend( $one );
});
...내부 코드를 함수로 자유롭게 감쌀 수 있습니다 :)
예제 fiddle에는 이벤트 보존을 보여주기 위해 추가 클릭 이벤트가 첨부되어 있습니다...
예제 피들:https://jsfiddle.net/ewroodqa/
...다음과 같은 경우에도 다양한 경우에 적용됩니다.
<div>
<div id="one">ONE</div>
</div>
<div>Something in the middle</div>
<div>
<div></div>
<div id="two">TWO</div>
</div>
jQuery 개체에서 선택한 두 항목을 스왑하려면 이 방법을 사용할 수 있습니다.
http://www.vertstudios.com/blog/swap-jquery-plugin/
나는 첨부된 이벤트로 부작용이 있기 때문에 스위치가 클론()을 사용하지 않는 솔루션을 원했습니다. 여기 제가 하게 된 것이 있습니다.
jQuery.fn.swapWith = function(target) {
if (target.prev().is(this)) {
target.insertBefore(this);
return;
}
if (target.next().is(this)) {
target.insertAfter(this);
return
}
var this_to, this_to_obj,
target_to, target_to_obj;
if (target.prev().length == 0) {
this_to = 'before';
this_to_obj = target.next();
}
else {
this_to = 'after';
this_to_obj = target.prev();
}
if (jQuery(this).prev().length == 0) {
target_to = 'before';
target_to_obj = jQuery(this).next();
}
else {
target_to = 'after';
target_to_obj = jQuery(this).prev();
}
if (target_to == 'after') {
target.insertAfter(target_to_obj);
}
else {
target.insertBefore(target_to_obj);
}
if (this_to == 'after') {
jQuery(this).insertAfter(this_to_obj);
}
else {
jQuery(this).insertBefore(this_to_obj);
}
return this;
};
두 개 이상의 DOM 요소를 포함하는 jQuery 개체와 함께 사용할 수 없습니다.
각 요소의 복사본이 여러 개 있는 경우 자연스럽게 루프에서 작업을 수행해야 합니다.저는 최근에 이런 상황이 있었습니다.전환해야 하는 두 개의 반복 요소에는 클래스와 컨테이너 디브가 있습니다.
<div class="container">
<span class="item1">xxx</span>
<span class="item2">yyy</span>
</div>
and repeat...
다음 코드를 통해 모든 것을 반복하고 역방향으로...
$( ".container " ).each(function() {
$(this).children(".item2").after($(this).children(".item1"));
});
나는 이 스니펫으로 그것을 했습니다.
// Create comments
var t1 = $('<!-- -->');
var t2 = $('<!-- -->');
// Position comments next to elements
$(ui.draggable).before(t1);
$(this).before(t2);
// Move elements
t1.after($(this));
t2.after($(ui.draggable));
// Remove comments
t1.remove();
t2.remove();
.after() .before()를 사용하는 objin 데이터베이스의 순서를 변경하기 위한 표를 작성했기 때문에 제가 실험한 결과입니다.
$(obj1).after($(obj2))
obj2 앞에 obj1을 삽입합니다.
$(obj1).before($(obj2))
그 반대로
그래서 만약 obj1이 obj3 다음에 있고 obj4 뒤에 있고, 당신이 장소를 바꾸고 싶다면 당신은 그것을 좋아할 것입니다.
$(obj1).before($(obj4))
$(obj2).before($(obj3))
이렇게 하면 됩니다. BTW에서 .prev()와 .next()를 사용하여 obj3와 obj4를 찾을 수 있습니다.
$('.five').swap('.two');
다음과 같은 jQuery 함수 만들기
$.fn.swap = function (elem)
{
elem = elem.jquery ? elem : $(elem);
return this.each(function ()
{
$('<span></span>').insertBefore(this).before(elem.before(this)).remove();
});
};
https://jsfiddle.net/ARTsinn/TVjnr/ 의 야닉 기네스 덕분입니다.
인 경우, 두 의 "A"와 "B", "B"를 .<tr>
찬마지에<tbody>
그냥 사용할 수 있습니다.$(trA).insertAfter($(trB))
또는$(trA).insertBefore($(trB))
교환하는 건 저한테 효과가 있어요 전화할 필요 없어요$(trA).remove()
클릭 를 다시 .$(trA)
현재 요소를 스왑하기 위해 주요 브라우저에 jquery를 사용할 필요가 없습니다. 돔 네티브돔방식이,,방식,insertAdjacentElement
위치에 상관없이 트릭을 수행합니다.
var el1 = $("el1");
var el2 = $("el2");
el1[0].insertAdjacentElement("afterend", el2[0]);
가장 좋은 옵션은 clone() 메서드로 복제하는 것입니다.
저는 당신이 그것을 아주 간단하게 할 수 있다고 생각합니다.예를 들어 다음 구조가 있다고 가정해 보겠습니다.
<div id="first">...</div>
<div id="second">...</div>
그리고 그 결과는 다음과 같아야 합니다.
<div id="second">...</div>
<div id="first">...</div>
jquery:
$('#second').after($('#first'));
도움이 되길 바랍니다!
언급URL : https://stackoverflow.com/questions/698301/is-there-a-native-jquery-function-to-switch-elements
'programing' 카테고리의 다른 글
제온을 위한 gcc 최적화 플래그? (0) | 2023.07.31 |
---|---|
PHP 이미지 업로드 보안 확인 목록 (0) | 2023.07.31 |
도커 exec으로 2개의 명령어를 실행하는 방법 (0) | 2023.07.31 |
Xcode 14에는 포드 번들을 위한 선택된 개발 팀이 필요합니다. (0) | 2023.07.31 |
부트스트랩에서 선택 선택 플러그인을 사용하여 선택 시 선택한 값을 설정하는 방법 (0) | 2023.07.31 |