how to use jquery 'replaceWith' twice in a document?

懵懂的女人 提交于 2020-01-16 13:16:13

问题


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:


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



来源:https://stackoverflow.com/questions/13064751/how-to-use-jquery-replacewith-twice-in-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!