jQuery prepend()的例子
prepend()方法是jQuery内置的方法,用于在所选元素的开头插入一个指定的内容。
语法:
$(selector).prepend(content, function)
参数:该方法接受上面提到的和下面描述的两个参数。
- content。这是一个必要参数,用于指定需要插入的内容。
- function。这是一个可选参数,用于指定调用后要执行的功能。
返回值:该方法返回选定的元素,以及predpend()方法所做的指定修改。
下面的例子说明了jQuery中的prepend()方法。
例子1:这个例子不包含可选参数。
<!DOCTYPE html>
<html>
<head>
<title>The prepend 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").prepend("Welcome to ");
});
});
</script>
<style>
div {
width: 350px;
height: 100px;
font-weight: bold;
padding:20px;
font-size: 25px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>GeeksforGeeks!</p>
<!-- Click on this button to see the change -->
<button>Click Here!</button>
</div>
</body>
</html>
输出:
在点击按钮之前。
点击按钮后。
例子2:这个例子包含可选参数。
<!DOCTYPE html>
<html>
<head>
<title>The prepend 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").prepend(function() {
return "<b>Hello ";
});
});
});
</script>
<style>
div {
width: 350px;
height: 100px;
font-weight: bold;
padding:20px;
font-size: 25px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>Contributor!</p>
<!-- Click on this button to see the change -->
<button>Click Here!</button>
</div>
</body>
</html>
输出:
在点击按钮之前。
点击按钮后。