复选框到 .detach 然后 .prepend 对象

Checkbox to .detach and then .prepend object

我想将 .detach 和 .prepend 与复选框一起使用,我发现这个函数与两个按钮一起使用:

$(document).ready(function(){
    var x;
    $("#btn1").click(function(){
        x = $("p").detach();
    });
    $("#btn2").click(function(){
        $("body").prepend(x);
    });
});

但是如何将它与复选框一起使用呢?当复选框被选中时,它会将元素添加到正文之前,当未选中时分离元素。

现在我正在使用淡入和淡出,但我想将其更改为分离和前置:

$('#toggle').change(function () {
    if (!this.checked) 
    //  ^
    $('.content').fadeOut('slow');
        else 
    $('.content').fadeIn('slow');
});

这个怎么样:-

var x;
$('#toggle').change(function() {
  if (!this.checked)
    x = $('.content').detach();
  else
    $('body').append(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>   

<input type="checkbox" id="toggle" checked="true" />

<div class="content">
  content content content content content content content content content content content content
</div>

检查 this 示例是否可以帮助您理解清楚。

<div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre><code>    $(document).ready(function() {
      var p;
      $("#trigger").change(function() {
        if (this.checked) {
          $('#mydiv').prepend(p);
          p = null;
        } else {
          p = $("p").detach();
        }
      });
    });
      p {
        background: yellow;
        margin: 6px 0;
      }
      p.off {
        background: black;
      }
    <!doctype html>
    <html lang="en">

    <head>
      <meta charset="utf-8">
      <title>detach demo</title>
      <link href="style.css" rel="stylesheet" />
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>

    <body>
      <div id="mydiv">
        <p>Hello</p>
        <p>you?</p>
      </div>
      Toggle:
      <input type="checkbox" name="mycheckbox" id="trigger" checked/>
      <script src="script.js"></script>
    </body>

    </html>

$(function () {
  var myCheck = $('input[name=myCheck]'),
      content = $('#content');
  myCheck.change(function(){
    if (myCheck.is(':checked')) {
      content.prependTo(document.body);
    } else {      
      content.detach();
    }
  });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="content"><span>Content</span></div>
  <label for="myCheck">
    <input type="checkbox" name="myCheck" checked="true">
    <span>My Check</span>
  </label>  
</body>
</html>