当前位置: 动力学知识库 > 问答 > 编程问答 >

html - jQuery move object to other container and back

问题描述:

I am struggling with this problem for a while. Lets say, I have imageA and imageB respectively in containerA and containerB. Additionally, I have containerC.

What I want to do, is:

  1. Click on imageA > imageB moves from containerB to containerC. imageA stays in containerA
  2. Click again on imageA > imageB moves from containerC back to containerB.
  3. Click on imageB > imageA moves from containerA to containerC.
  4. etc.

At this moment, I can move imageA and imageB to containerC, but I can't move them back to original places.

HTML code:

<div id="containerA">

<img id="imageA" src="http://www.w3schools.com/images/tryitimg.gif" alt="imageA">

</div>

<div id="containerB">

<img id="imageB" src="http://www.w3schools.com/images/w3logotest2.png" alt="imageB">

</div>

JavaScript code:

$(window).load(function(){

$("#imageA").on('click', function() {

$("#imageB").appendTo($("#containerC"));

});

$("#imageB").on('click', function() {

$("#imageA").appendTo($("#containerC"));

});

});

Any ideas how to do that?

网友答案:

change the markup to

<div id="containerA">
    <img id="imageA" src="http://www.w3schools.com/images/tryitimg.gif" alt="imageA">
</div>

<div id="containerB">
    <img id="imageB" src="http://www.w3schools.com/images/w3logotest2.png" alt="imageB">
</div>

<div id="containerC"></div>

and do

$(function(){
    $("#imageA").on('click', function() {
        var container = $("#imageB").closest("#containerC").length ? $("#containerA") : $("#containerC");
        $("#imageB").appendTo(container);
    });

    $("#imageB").on('click', function() {
        var container = $("#imageA").closest("#containerC").length ? $("#containerB") : $("#containerC");
        $("#imageA").appendTo(container);
    });
});

FIDDLE

分享给朋友:
您可能感兴趣的文章:
随机阅读: