jquery在点击时将div交换为新div

时间:2016-03-14 20:45:12

标签: jquery

我想要有2个div,当你点击div中的某个特定元素时,将整个div移动到一个新的div,如果点击则再次返回。

我有一些工作,但它只是移动了特定的一个类,而不是包装它的整个div。

http://jsfiddle.net/uw446/249/

<div class="lineup-table">
       <div  id="choose-players" class="player-left">
         <div id="lineup" class="player-row"><a>Players Name 1</a><a class="swap">SWAP 1</a></div>
         <div id="lineup" class="player-row"><a>Players Name 2</a><a class="swap">SWAP 2</a></div>
       </div>
       <div  id="selected-players" class="player-right">
         <div id="lineup" class="player-row-selected"><a>Players Name 1</a><a class="swap">SWAP 3</a></div>
         <div id="lineup" class="player-row-selected"><a>Players Name 2</a><a class="swap">SWAP 4</a></div>
       </div>
</div>

这是我到目前为止的功能,但再次无法正常工作

$(".swap").on("click", function() {
    var $this = $(this);        
     if($(this).closest("#lineup").length>0){
        $this.removeClass("player-row").addClass("player-row-selected").prependTo("#selected-players");
    } else {
        $this.removeClass("player-row-selected").addClass("player-row").prependTo("#choose-players");
    }
});

2 个答案:

答案 0 :(得分:1)

注意ID:它们必须是唯一的。所以要有多个id =&#34;阵容&#34;你可以添加阵容作为附加类,并使用ids阵容后跟一个数字。

此外,您需要检查当前元素是否在播放器左下方,以便决定要执行的操作:

&#13;
&#13;
$(function () {
  $(".swap").on("click", function() {
    var $thisDiv = $(this).closest(".lineup");
    if($thisDiv.closest(".player-left").length>0){
      $(this).removeClass("player-row").addClass("player-row-selected");
      $thisDiv.closest(".lineup").prependTo("#selected-players")
    } else {
      $(this).removeClass("player-row-selected").addClass("player-row");
      $thisDiv.closest(".lineup").prependTo("#choose-players");
    }
  });
});
&#13;
.lineup-table { width:400px }
.player-left,.player-right { width:196px; display: inline-block;border: 1px solid red; vertical-align:top }
.player-row-selected, .player-row{ height:50px; background-color:#ccc; cursor:pointer;border:1px solid black;margin:5px}
&#13;
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<div class="lineup-table">
    <div  id="choose-players" class="player-left">
        <div id="lineup1" class="lineup player-row"><a>Players Name 1</a><a class="swap">SWAP 1</a></div>
        <div id="lineup2" class="lineup player-row"><a>Players Name 2</a><a class="swap">SWAP 2</a></div>
    </div>
    <div  id="selected-players" class="player-right">
        <div id="lineup3" class="lineup player-row-selected"><a>Players Name 3</a><a class="swap">SWAP 3</a></div>
        <div id="lineup4" class="lineup player-row-selected"><a>Players Name 4</a><a class="swap">SWAP 4</a></div>
    </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试定位包含div

$('#lineup').on('click', '.swap', function

这样,目标在文档加载后永远不会改变位置。