如何在文档中两次使用jquery'replaceWith'?

时间:2012-10-25 08:40:02

标签: jquery replacewith

我试图在点击时激活一个jQuery'replaceWith'函数,用div2替换div1然后再次使用'replaceWith'将div2替换为div1。

一切正常,但是当点击div2时,div1不会重新出现。

我的代码是:

$(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"));
});
});​

近乎工作的jsfiddle在这里:

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

我很确定我的问题已在下面的链接中得到解答,但我无法弄清楚如何将其应用于我的确切代码。

Events not registering after replaceWith

谢谢你。

1 个答案:

答案 0 :(得分:3)

而不是替换你可以使用show()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