关于<div with =“”id =“

时间:2016-01-02 10:46:51

标签: jquery

=“”

上的replaceWith函数我有一个HTML和javascript / Jquery代码,它被分成几个div整个页面。我有兴趣使用按钮功能和jquery来互相替换DIV内容或使用不同的内容。例如,在下面的代码中,如果我按下带有id =&#34; DIV1&#34;的按钮,我想用ID =#log3替换带有ID =#log2内容的DIV和DIV。

At the moment it does not function like it should, when I press the button with the id="DIV1", the entire page including the positions of the DIV which were previously set in the STYLE sheet are replaced. So everything disappears, and I get only the content of the DIV with the id=#log3 placed at the top of the page, without using any style sheets. 

How can I fix this, because I want to replace the contents of the DIV with each other, or with new content, without losing the positions of the DIV across the page from STYLE sheet, or I want to place new content into the DIV without redefining its position on the page?


    <html>
    <head>
      <script>
        $function(){
           $("#DIV1").click(function() {
                 $("#log2").replaceWith("#log3");
                 $("#log3").replaceWith("");
                 $("#log6").replaceWith("");
           });
        }
      </script>
      <style type="text/css">

        #log2 {

          top: 15%;
          left: 1%;

        }

        #log3 {

          top: 15%;
          left: 10%;

        }
    </style>
    </head>
    <body>
           <button type="button" id="DIV1" size="64">Button DIV1</button>

           <div id="log2" style="text-align:center; width: 13%; height:60%;">
                 <p> This is the first Text. </p>
           </div>

           <div id="log3" style="text-align:center; width: 13%; height:60%;">
                 <p> This is the second Text. </p>
           </div>



    </body>
    </html>

1 个答案:

答案 0 :(得分:2)

你应该知道的事情

  

.replaceWith()方法从DOM中删除内容并插入新内容   通过一次通话即可获得内容。

所以在您的代码中

$("#log2").replaceWith("#log3");

将取代

<div id="log2" style="text-align:center; width: 13%; height:60%;">
      <p> This is the first Text. </p>
</div>

<div id="log3" style="text-align:center; width: 13%; height:60%;">
    <p> This is the second Text. </p>
</div>

您可能需要使用.html().insertAfter().insertBefore()

$("#log2").html($("#log3").html());