jQuery clone()方法
clone()方法是jQuery内置的方法,用于复制所选元素,包括其子节点,文本和属性。
语法:
$(selector).clone(true|false)
参数:该方法接受一个可选的参数,可以是true或false,指定是否应该复制事件处理程序。
返回值:它返回选定元素的克隆元素。
例子1:在这个例子中,clone()方法不包含任何参数。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!--In this example no parameter is passing
to the clone method-->
<script>
(document).ready(function () {
("button").click(function () {
$("p").clone().appendTo("body");
});
});
</script>
</head>
<body>
<p>Welcome to</p>
<p>GeeksforGeeks !!!</p>
<!-- Click on this method and see
the clone element-->
<button>Click Me!</button>
</body>
</html>
输出:
例子2:在下面的代码中,true被传递给了clone方法。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Here clone method is called with the
true passed value -->
<script>
(document).ready(function () {
("button").click(function () {
("body").append(("p:first").clone(true));
});
("p").click(function () {
(this).animate({
fontSize: "+=1px"
});
});
});
</script>
</head>
<body>
<p>GeeksforGeeks !</p>
<p>Hello Writer !</p>
<!-- Click on this method and see
the clone element -->
<button>Click Me!</button>
</body>
</html>
在这个例子中,当你点击 “GeeksforGeeks “时,代码事件处理程序animate将发挥作用,这也将反映在克隆的元素上。
输出: