before、insertBefore都可以在元素前面添加元素。稍有不同的是要添加的元素在statement中的位置。
$('.prettyBox').before("
Iron man
");
$("
Iron man
").insertBefore('.prettyBox');
.prettyBox{
padding:8px;
background: grey;
margin-bottom:8px;
width:300px;
height:100px;
}
.newPrettybox{
padding:8px;
background: red;
margin-bottom:8px;
width:200px;
height:50px;
}
jQuery before() and insertBefore() example
Ip man
Ip man 2
before()
insertBefore()
reset
$("#before").click(function () {
$('.prettyBox').before("
Iron man
");
});
$("#insertBefore").click(function () {
$("
Iron man
").insertBefore('.prettyBox');
});
$("#reset").click(function () {
location.reload();
});