how to use jquery 'replaceWith' twice in a

2019-08-23 01:44发布

i am trying to activate a jQuery 'replaceWith' function on click to replace div1 with div2 and then use 'replaceWith' again to replace div2 with div1 on click.

everything is working except, when clicking on div2, div1 does not re-appear.

my code is:

$(document).ready(function(){
$("#open_doors").click(function(){
$("#leftdoor_inner").animate({"left": "-=164px"}, 'slow');
$("#leftdoor_outer").animate({"left": "-=74px"},'slow');
$("#rightdoor_inner").animate({"left": "+=164px"},'slow');
$("#rightdoor_outer").animate({"left": "+=74px"},'slow');
$("#open_doors").replaceWith($("#close_doors"));
});
$("#close_doors").click(function(){
$("#leftdoor_inner").animate({"left": "+=164px"},'slow');
$("#leftdoor_outer").animate({"left": "+=74px"},'slow');
$("#rightdoor_inner").animate({"left": "-=164px"},'slow');
$("#rightdoor_outer").animate({"left": "-=74px"},'slow');
$("#close_doors").replaceWith($("#open_doors"));
});
});​

the nearly working jsfiddle is here:

http://jsfiddle.net/9zsdN/2/

i'm pretty sure my question has been answered at the link below but i can't figure out how to apply it to my exact code.

Events not registering after replaceWith

thank you.

1条回答
女痞
2楼-- · 2019-08-23 02:32

instead of replaceWith you can just use show() and hide()

 $(document).ready(function(){
      $("#open_doors").click(function(){
        $("#leftdoor_inner").animate({"left": "-=164px"}, 'slow');
        $("#leftdoor_outer").animate({"left": "-=74px"},'slow');
        $("#rightdoor_inner").animate({"left": "+=164px"},'slow');
        $("#rightdoor_outer").animate({"left": "+=74px"},'slow');
        $("#open_doors").hide();
        $("#close_doors").show();
      });
     $("#close_doors").click(function(){
         $("#leftdoor_inner").animate({"left": "+=164px"},'slow');
         $("#leftdoor_outer").animate({"left": "+=74px"},'slow');
         $("#rightdoor_inner").animate({"left": "-=164px"},'slow');
         $("#rightdoor_outer").animate({"left": "-=74px"},'slow');
         $("#close_doors").hide();
         $("#open_doors").show();
     });
   });

Demo

查看更多
登录 后发表回答