prepend()方法是jQuery中的內置方法,用於在選定元素的開頭插入指定的內容。
用法:
$(selector).prepend(content, function)
參數:該方法接受上述和以下所述的兩個參數:
- content:這是必需的參數,用於指定需要插入的內容。
- function:它是可選參數,用於指定調用後要執行的函數。
返回值:此方法返回通過prepend()方法進行指定更改的所選元素。
以下示例說明了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 woirking 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 Metho</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the woirking 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>
輸出:
在單擊按鈕之前:
單擊按鈕後:
相關用法
- JQuery after()用法及代碼示例
- JQuery val()用法及代碼示例
- JQuery first()用法及代碼示例
- JQuery has()用法及代碼示例
- JQuery on()用法及代碼示例
- JQuery one()用法及代碼示例
- JQuery eq()用法及代碼示例
- JQuery last()用法及代碼示例
- JQuery focus()用法及代碼示例
- JQuery index()用法及代碼示例
- JQuery hasClass()用法及代碼示例
- JQuery queue()用法及代碼示例
- JQuery stop()用法及代碼示例
注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery | prepend() with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。