jquery before()和insertBefore()函數執行個體

來源:互聯網
上載者:User

在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>

效果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.