appendTo( ) 方法可用于在被选元素的开头插入 HTML 元素。
语法格式:
$(content).prependTo(selector)
参数如下:
content:插入的内容,必须包含 HTML 标签。
selector:规定把内容添加至哪个元素的开头。
注意:若 content 为页面中原本已经存在的元素,那么它将被从原来的位置移除,并在被选元素的开头被插入。
示例:
(1)插入新列表项
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<li>banana</li>").prependTo($(".list"));
})
})
</script>
<style>
.list li {
width: 200px;
height: 30px;
line-height: 30px;
font-size: 16px;
font-weight: 700;
margin-bottom: 5px;
background-color: rgba(9, 6, 163, 0.411);
}
</style>
</head>
<body>
<button>按钮</button>
<ul class="list">
<li>apple</li>
</ul>
</body>
</html>
点击按钮,将添加新的列表项至列表的开头,如图:
(2)添加页面中原本存在的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".para").prependTo($(".box"));
})
})
</script>
<style>
.box {
width: 200px;
height: 200px;
background-color: rgba(37, 204, 59, 0.486);
}
.para {
width: 200px;
height: 30px;
line-height: 30px;
background-color: rgba(118, 11, 218, 0.425);
}
</style>
</head>
<body>
<button>按钮</button>
<p class="para">这是一个段落。</p>
<div class="box">
<p>普通段落。</p>
</div>
</html>
点击按钮,段落将被从原来的位置移除,并添加到盒子的开头,如图: