jQuery wrap()的例子
wrap()方法是jQuery内置的一个方法,用于将指定的元素包裹在选定的元素周围。
语法:
$(selector).wrap(element, function)
参数:该方法接受上面提到的和下面描述的两个参数。
- element。这是一个必要的参数,用于指定环绕选定元素的元素。
- function。这是一个可选参数,用于指定返回包装元素的函数。
返回值:该方法返回选定的元素和wrap()方法所做的指定修改。
下面的例子说明了jQuery中的wrap()方法。
实例1:本实例不接受可选参数。
<!DOCTYPE html>
<html>
<head>
<title>The wrap() Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function() {
("button").click(function() {
$("p").wrap("<div></div>");
});
});
</script>
<style>
div {
background-color: lightgreen;
padding: 20px;
width: 200px;
font-weight: bold;
height: 60px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this paragraph and see the change -->
<p>Welcome to GeeksforGeeks!</p><br>
<button>Click Here!</button>
</body>
</html>
输出:
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>The wrap Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function() {
("button").click(function() {
$("p").wrap(function() {
return "<div></div>"
});
});
});
</script>
<style>
div {
background-color: lightgreen;
padding: 20px;
width: 200px;
font-weight: bold;
height: 60px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this paragraph and see the change -->
<p>Welcome to GeeksforGeeks!</p><br>
<button>Click Here!</button>
</body>
</html>
输出: