使用 jQuery 切换 2 个 div 的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9030322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:13:24  来源:igfitidea点击:

Switch positions of 2 divs with jQuery

jqueryhtml

提问by Cybercampbell

I'm wondering if it's posible to switch positions of two divs with jQuery.

我想知道是否可以用 jQuery 切换两个 div 的位置。

I have two div like this

我有两个这样的 div

<div class="div1">STUFF ONE</div>
<div class="div2">STUFF TWO</div>

so if div2has content (or contains more than just white spaces) it switches the order of div1and div2

因此,如果div2有内容(或包含的不仅仅是空格),它会切换div1div2

so this:

所以这:

<div class="div1">STUFF ONE</div>
<div class="div2">STUFF TWO</div>

would become this:

会变成这样:

<div class="div2">STUFF TWO</div>
<div class="div1">STUFF ONE</div>

But if it was this:

但如果是这样:

<div class="div1">STUFF ONE</div>
<div class="div2"></div>

or this:

或这个:

<div class="div1">STUFF ONE</div>
<div class="div2">    </div>

it wouldn't do anything.

它不会做任何事情。

Also... if posible, if switched I would like to add a class to div1.

另外...如果可能的话,如果切换我想添加一个类到div1.

Any help with this will be very much appreciated.

对此的任何帮助将不胜感激。

UPDATE:

更新:

I forgot to add that I have to run this across multipul instanses on the same page.

我忘了补充一点,我必须在同一页面上的多个实例中运行它。

Each instance is formated like this:

每个实例的格式如下:

<div class="view-container"> 
  <div class="view-content"> 
   <div class="views-row">
     <div class="div1">STUFF ONE</div>
     <div class="div2">STUFF TWO</div>
   </div>
   <div class="views-row">
     <div class="div1">STUFF ONE</div>
     <div class="div2">STUFF TWO</div>
   </div>
  </div>
</div>

回答by Rusty Fausak

I'll throw in my solution

我会提出我的解决方案

$('.div2:parent').each(function () {
    $(this).insertBefore($(this).prev('.div1'));
});

Edit: Doesn't work for whitespace in div2. Here's an updated solution:

编辑:不适用于 div2 中的空格。这是一个更新的解决方案:

$('.div2').each(function () {
    if (!$(this).text().match(/^\s*$/)) {
        $(this).insertBefore($(this).prev('.div1'));
    }
});

回答by Vigrond

Here's an example:

下面是一个例子:

http://jsfiddle.net/52xQP/1/

http://jsfiddle.net/52xQP/1/

First you want to clone the elements. Then, check a condition if div2 is empty. Then, do the swap:

首先,您要克隆元素。然后,如果 div2 为空,则检查条件。然后,进行交换:

div1 = $('#div1');
div2 = $('#div2');

tdiv1 = div1.clone();
tdiv2 = div2.clone();

if(!div2.is(':empty')){
    div1.replaceWith(tdiv2);
    div2.replaceWith(tdiv1);

    tdiv1.addClass("replaced");
}

回答by Farmor

if(div1First){
 var div2 = ($('.div2')).detach();
 ($('.div1')).append(div2);
}else{
 var div1 = ($('.div1')).detach();
 ($('.div2')).append(div1);
}

Fiddle to try it.

摆弄试试吧。

回答by David Richard

var row2content = $('.div2').html();                //Get row 2s content
row2contentnospaces = row2content.replace(' ', ''); //Eliminate whitespace
if(!(row2contentnospaces == '')){                   //Check if row2 is empty
    var row2 = $('.div2');                          //Get row 2
    $('.div2').remove();                            //remove row2
    $('.div1').before(row2);                        //add row 2 before row 1
}

回答by Grrbrr404

Well ... why are you trying to change the POSITION of the div elements. Does it matter? Why not changing the CONTENT?

嗯……你为什么要改变 div 元素的 POSITION。有关系吗?为什么不改变内容?

var divOneText = $('#div1').html();
var divTwoText = $('#div2').html();

if (divOneText != '' && divTwoText != '') {
  $('#div1').html(divTwoText);
  $('#div2').html(divOneText);
}

Add trim() if you want to remove whitespace.

如果要删除空格,请添加 trim() 。

回答by Hubbitus

I've found elegant jQuery plugin in 4 lines for that. Author Yannick Guinness.

为此,我在 4 行中找到了优雅的 jQuery 插件。作者亚尼克·吉尼斯

/**
 * Swap an element with another one
 * @author: Yannick Guinness
 * @version: 0.1
 *
 * @params {Object} element - object that has to be swapped
 * @return: {jQuery Object}
 *
 * @usage:
 *     $('.one').swap('.two');
 *
 * @license: MIT
 * @date: 2013/07/22
 **/
$.fn.swap = function (elem) {
    elem = elem.jquery ? elem : $(elem);
    return this.each(function () {
        $(document.createTextNode('')).insertBefore(this).before(elem.before(this)).remove();
    });
};

$('.one').on('click', function () {
    alert(true);
});

$('input').click(function () {
    $('.one').swap('.two');
});

Run it in fiddle

在小提琴中运行它

While @Vigront's answer simple and great (I've upvoted it), it has one serious drawback - on cloning elements loose events, bound to them...

虽然@Vigront 的回答简单而伟大(我已经赞成),但它有一个严重的缺点——克隆元素松散事件,绑定到它们......

That plugin do not have such the problem. And even fiddle contains click event to demonstrate it.

那个插件没有这样的问题。甚至小提琴包含单击事件来演示它。