简体   繁体   English

交换div在某个指数处的位置

[英]Swap div's position at certain index

I am trying to swap a div's position from top on and when I click another div then top div can be swap. 我试图从顶部开始交换div的位置,当我点击另一个div然后顶部div可以交换。

My HTML 我的HTML

<div class="wrap top">
    <input type="text" value="div1" class="textbox " />
</div>

<div class="wrap">
    <input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
    <input type="text" value="div3" class="textbox " />
</div>

jQuery jQuery的

var objectDivs = $('.wrap');
objectDivs.on('click', function() {
    var $this = $(this);
    objectDivs.eq(0).html($this);
    $this.remove();
})

The fact is I don't want to remove the div which I click instead want to swap the positions around. 事实是我不想删除我点击的div而不想交换周围的位置。

How Can I do this using jQuery itself? 我怎么能用jQuery本身做到这一点?

 $(".wrap").on("click", function(){ $(this).parent().prepend(this); }); 
 .wrap{background:#eee;padding:10px; margin:10px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <div class="wrap">1</div> <div class="wrap">2</div> <div class="wrap">3</div> </div> 

You should try to use insertBefore and insertAfter for this. 您应该尝试使用insertBefore和insertAfter。 For example: - 例如: -

 (function($) { $(".wrap").on("click", function() { if ($(this).index() == 0) { $(this).insertAfter($(this).next()); } else { $(this).insertBefore($(this).prev()); } }); }(jQuery)); 
 .wrap { width: 50px; height: 50px; } .wrap1 { background: red; } .wrap2 { background: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="wrapper"> <div class="wrap wrap1"></div> <div class="wrap wrap2"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM