在jquery中,prepend()与prependTo()函数有着相同的功能,完成相同的事。即添加一个文本或html内容到匹配元素内容的前面。其主要的差别是语法上的差别。
例如:
<divclass="box">I'm a big box</div>
<divclass="box">I'm a big box 2</div>
$('.box').prepend("<divclass='newbox'>I'm new box by prepend</div>");
$("<divclass='newbox'>I'm new box by prependTo</div>").prependTo('.box');
结果:
<divclass="box">
<divclass='newbox'>I'm new box by prepend</div>
I'm a big box
</div>
<divclass="box">
<divclass='newbox'>I'm new box by prepend</div>
I'm a big box 2
</div>
具体代码:
<html>
<head>
<script type="text/javascript" src="../jquery-1.11.1.min.js"></script>
<style type="text/css">
.box{
padding:8px;
border:1px solid blue;
margin-bottom:8px;
width:300px;
height:100px;
}
.newbox{
padding:8px;
border:1px solid red;
margin-bottom:8px;
width:200px;
height:50px;
}
</style>
</head>
<body>
<h1>jQuery prepend() and prependTo example</h1>
<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>
<p>
<button id="prepend">prepend()</button>
<button id="prependTo">prependTo()</button>
<button id="reset">reset</button>
</p>
<script type="text/javascript">
$("#prepend").click(function () {
$('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");
});
$("#prependTo").click(function () {
$("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');
});
$("#reset").click(function () {
location.reload();
});
</script>
</body>
</html>
效果图: