jQuery将一个元素移到另一个元素中
有两种方法可以将一个元素移到另一个元素里面,如下所示。
方法1:使用append()方法 : jQuery中的这个append()方法是用来在所选元素的末端插入一些内容。
语法:
$(selector).append( content, function(index, html) )
参数:该方法接受上面提到的和下面描述的两个参数。
- content。这是一个必要的参数,用于指定要插入到所选元素末尾的内容。内容的可能值是HTML元素,jQuery对象和DOM元素。
- function(index, html)。这是一个可选参数,用于指定将返回要插入的内容的函数。
- index。它用于返回元素的索引位置。
- html。它用于返回所选元素的当前HTML。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#child {
height: 40px;
width: 100px;
margin: 0 auto;
color: yellow
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br>
<h4 id= "child">
A Computer Science Portal for geeks
</h4>
<br>
<button onclick="myGeeks()">
move
</button>
<!-- Script to move element -->
<script>
function myGeeks() {
("#parent").append(("#child"));
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法2:使用prepend()方法 : prepend()方法是jQuery内置的方法,用于在选定元素的开头插入一个指定的内容。
语法:
$(selector).prepend(content, function)
参数:该方法接受上面提到的和下面描述的两个参数。
- content。这是一个必要参数,用于指定需要插入的内容。
- function。这是一个可选参数,用于指定调用后要执行的功能。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#child {
height: 40px;
width: 100px;
margin: 0 auto;
color: yellow
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br>
<h4 id= "child">
A Computer Science Portal for geeks
</h4>
<br>
<button onclick="myGeeks()">
move
</button>
<!-- Script to move element -->
<script>
function myGeeks() {
("#parent").prepend(("#child"));
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。