在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>
效果: