如何使用jQuery克隆一个块

如何使用jQuery克隆一个块

jQuery中的Clone方法执行一组匹配元素的深度拷贝。你可以创建一个数据的副本以及一个事件处理程序的副本。

语法:

$(selector).clone(true|false)

参数值:

  • True指定事件处理程序也应该被复制。
  • False(Default)种类,事件处理程序不应该被复制。

例子1:在这个例子中,我们没有向克隆方法传递任何值。

<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript" src=
        "https://code.jquery.com/jquery-1.12.0.min.js">
    </script>
      
    <style>
        #info {
            justify-content: center;
            width: 50%;
        }
  
        #container {
            border: 4px outset red;
            background-color: lightblue;
            justify-content: center;
            width: 50%;
        }
  
        #btn {
            background-color: #4CAF50;
            color: white;
            padding: 15px 32px;
            text-align: center;
            display: inline-block;
            font-size: 16px;
        }
    </style>
  
    <script>
        (document).ready(function () {
            ("button").click(function () {
                $("#info").clone().appendTo("#container");
            });
        });
    </script>
</head>
  
<body>
    <div id="info">
        <h4>Clone() method<h4>
          
        <p>
            The .clone() method performs a deep 
            copy of the set of matched elements,
            meaning that it copies the matched 
            elements as well as all of their
            descendant elements and text nodes.
        </p>
    </div>
  
    <button id="btn"> Learn More</button>
    <br><br>
      
    <div id="container">
        <h3> Result </h3>
    </div>
</body>
  
</html>

输出:

如何使用jQuery克隆一个块?

例2:在这个例子中,我们将 “true “值传递给复制事件处理程序的clone方法。这里我们要改变段落的背景颜色,只要用户点击该段落。正如你在输出中看到的那样,这将被复制。

<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript" src=
        "https://code.jquery.com/jquery-1.12.0.min.js">
    </script>
  
    <style>
        body {
            background-color: lightblue;
        }
  
        #main {
            text-align: center;
            margin: 20px 300px;
            padding: 10px;
            background-color: #00b3b3;
            display: inline-block;
            position: absolute;
        }
  
        button {
            padding: 20px;
            font-size: 30px;
            margin-top: 05px;
        }
  
        p {
            padding: 10px;
            font-size: 28px;
        }
    </style>
      
    <script>
        (document).ready(function () {
            ("button").click(function () {
                ("body").append(("p:first").clone(true));
            });
  
            ("p").click(function () {
                (this).css("background-color", "yellow");
            });
  
        });
    </script>
</head>
  
<body>
    <div id="main">
        <button id="clone"> Clone </button>
    </div>
  
    <p>Clone method example</p>
</body>
  
</html>

输出:

如何使用jQuery克隆一个块?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

jQuery 方法