我可以很容易地交换两个元素字?

我想要做这一行,如果可能的。

我有一个选择元和我有两个按钮上或向下移动的选项,而且我已经有选择的和目标选择,我这样做与一个如果,但我想知道如果有一个更简单的方法。

有帮助吗?

解决方案

我发现了一个有趣的方式来解决这个只使用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个元件,否则它可以给奇怪的结果。

有很多边缘情况对这个问题,这是不被接受的答案或bobince的回答来处理。涉及克隆其他的解决方案是在正确的轨道上,但克隆是昂贵的和不必要的。我们很想克隆,因为如何交换两个变量,其中的步骤之一是分配一个变量给一个临时变量的老问题。不需要分配,(克隆),在这种情况下。这里是一个基于jQuery的溶液:

function swap(a, b) {
    a = $(a); b = $(b);
    var tmp = $('<span>').hide();
    a.before(tmp);
    b.before(a);
    tmp.replaceWith(b);
};

很多这些答案仅仅是错误的,一般情况下,其它的是不必要的复杂,如果他们其实连工作。 jQuery的.before.after方法做你最想做的事,但你需要一个第三个元素的方法很多交换算法的工作。这是很简单 - 让临时DOM元素作为一个占位符,而你走动的东西。有没有必要看父母或兄弟姐妹,当然也没有需要克隆...

$.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.after($that).remove();

  return $this;
}

1)把临时的div temp this

2)this之前移动that

3)that后移动temp

3b)中除去temp

然后,只需

$(selectorA).swapWith(selectorB);

样本: http://codepen.io/anon/pen/akYajE

您不应该需要两个克隆,人会做。以保罗Bergantino答案,我们有:

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时,才需要,如果你不能确保,总是有befor的元件(在我的情况下,它是)

这是我的解决办法,以向上和向下移动多个子元素的父元素的内部。 可以很好地用于在列表框移动选择的选项(<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对象中选定的两个项目,则可以使用此方法

http://www.vertstudios.com/blog/swap-jquery-插件/

我想一个解决方案巫不使用克隆(),因为它具有附带事件副作用,这里是我最终做

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为这样:

<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();

我做了表在数据库中使用。经过()。之前()改变obj的顺序,所以这是从我的实验。

$(obj1).after($(obj2))

时OBJ2之前插入OBJ1和

$(obj1).before($(obj2)) 

执行,反之亦然。

所以,如果OBJ1是OBJ4后OBJ 3和OBJ 2之后,如果你想改变的地方OBJ1和OBJ2,你会做这样

$(obj1).before($(obj4))
$(obj2).before($(obj3))

此应该这样做 顺便说一句,你可以使用.prev()和的.next()来找到OBJ 3和OBJ4如果没有某种指数为它了。

如果nodeA和nodeB上是兄弟,喜欢2个<tr>在同一<tbody>,你可以只使用$(trA).insertAfter($(trB))$(trA).insertBefore($(trB))交换它们,它为我工作。你不需要之前调用$(trA).remove(),否则你需要重新绑定上$(trA)一些点击事件

最好的选择是与clone()方法克隆它们。

我认为你可以做到这一点很简单。例如,让我们说你有一个结构: ...

<div id="first">...</div>
<div id="second">...</div>

和的结果应该是

<div id="second">...</div>
<div id="first">...</div>

jquery的:

$('#second').after($('#first'));

我希望它能帮助!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top