jQuery wrapInner()的应用实例
wrapInner()方法是jQuery的一个内置方法,用于将HTML元素包裹在每个选定元素的内容中。
语法:
$(selector).wrapInner(wrap_element, function(index))
参数:该函数接受上面提到的和下面描述的两个参数。
- wrap_element:这是一个强制性参数,用于指定环绕所选元素内容的HTML元素。
- function。它是可选参数,用于指定返回包装元素的函数。
- index。它返回元素的索引。
返回值:该方法返回所选择的元素和应用的变化。
下面的例子说明了jQuery中的wrapInner()方法。
例子1:这个例子不包含可选参数。
<!DOCTYPE html>
<html>
<head>
<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() {
("div").click(function() {
$(this).wrapInner("<b></b>").css(
"background-color", "green");
});
});
</script>
<style>
body {
width: 200px;
padding: 20px;
height: 20px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this div and see the change -->
<div>Welcome to GeeksforGeeks!</div>
</body>
</html>
输出:
在点击div元素之前。
点击div元素后。
示例 2:
<!DOCTYPE html>
<html>
<head>
<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() {
("div").click(function() {
$("span").wrapInner(function(n) {
return "<i></i>";
});
});
});
</script>
<style>
body {
width: 250px;
padding: 20px;
height: 20px;
font-size: 20px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this div and see the change -->
<div>Welcome to <span>GeeksforGeeks!</span></div>
</body>
</html>
输出:
在点击div元素之前。
点击div元素后。