本文示範如何使用 jQuery 的 prepend() 方法,在元素內部的最前面插入新內容,可用於文字段落前與列表前新增項目。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>
</html>
prepend() 與 append() 剛好相反:前者插入到「內部最前面」,後者插入到「內部最後面」。因此用它為 <ol> 前插 <li>,新項目會排在所有項目之前。希望本文對大家的 jQuery 開發有所幫助。