jQuery prepend()和prependTo()方法都执行相同的任务,在匹配元素的内容之前添加文本或html内容。 主要区别在于语法。
例如,
<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>
1. $('selector')。prepend('new text');
$('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");
2. $('new text')。prependTo('selector');
$("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');
结果
以上两种方法都执行相同的任务,但是使用不同的语法, prepend()或prependTo()之后的新内容将变为
这确实是多功能工具。 对于要在其上使用滑块的任何网站,这都是这样做的方法。 如果您查看任何大型网站,例如www.o2.co.uk/之类的网站,或电影网站,您很可能会看到一个正在使用的网站。 这是一种使图像旋转看起来很灵巧并吸引观看者眼球的好方法。 它为您的网站增加了不同的维度,使其真正脱颖而出。
<div class="box">
<div class='newbox'>I'm new box by prepend</div>
I'm a big box
</div>
<div class="box">
<div class='newbox'>I'm new box by prepend</div>
I'm a big box 2
</div>
自己尝试
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.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>
翻译自: https://mkyong.com/jquery/jquery-prepend-and-prependto-example/