在jquery中,before()和insertBefore()函数都有着一样的功能,一样的目的,也就是添加文本或html内容到匹配元素的前面,其主要的区别在于语法上的区别。
例如:
<divclass="prettyBox">I'm a ipman</div>
<divclass="prettyBox">I'm a ipman 2</div>
1 $(‘selector’).before(‘new content’);
$(‘.prettyBox’).before(“<div class=”newPrettybox”>Ironman</div>”);
2 $(‘new content’).insertBefore(‘selector’);
$("<divclass='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');
结果:
以上的两个方法都是完成相同的任务,但是在语法上是不一样的,其结果如下:
<divclass='newPrettybox'>Iron man</div>
<divclass="prettyBox">
I'm a ipman
</div>
<divclass='newPrettybox'>Iron man</div>
<divclass="prettyBox">
I'm a ipman 2
具体的代码如下:
<html>
<head>
<script type="text/javascript" src="../jquery-1.11.1.min.js"></script>
<style type="text/css">
.prettyBox{
padding:8px;
background:grey;
margin-bottom:8px;
width:300px;
height:100px;
}
.newPrettybox{
padding:8px;
background:red;
margin-bottom:8px;
width:200px;
height:50px;
}
</style>
</head>
<body>
<h1>jquery before() and insertBefore() example</h1>
<div class="prettyBox">ip man</div>
<div class="prettyBox">ip man2</div>
<p>
<button id="before">before()</button>
<button id="insertBefore">insertBefore()</button>
<button id="reset">reset</button>
</p>
<script type="text/javascript">
$("#before").click(function(){
$('.prettyBox').before("<div class='newPrettyBox'>iron man</div>");
});
$("#insertBefore").click(function(){
$("<div class='newPrettybox'>iron man</div>").insertBefore('.prettyBox');
});
$("#reset").click(function(){
location.reload();
});
</script>
</body>
</html>
效果: