jQuery - 添加元素
添加新的 HTML 內(nèi)容
我們將學(xué)習(xí)用于添加新內(nèi)容的四個(gè) jQuery 方法:
append() - 在被選元素的結(jié)尾插入內(nèi)容
prepend() - 在被選元素的開頭插入內(nèi)容
after() - 在被選元素之后插入內(nèi)容
before() - 在被選元素之前插入內(nèi)容
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>追加文本</b>。"); }); $("#btn2").click(function(){ $("ol").append("<li>追加列表項(xiàng)</li>"); }); }); </script> </head> <body> <p>段落。</p> <p>另一個(gè)段落。</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1">添加文本</button> <button id="btn2">添加列表項(xiàng)</button> </body> </html>
prepend() 方法
jQuery prepend() 方法在被選元素的開頭插入內(nèi)容。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").prepend("<b>在開頭追加文本</b>。 "); }); $("#btn2").click(function(){ $("ol").prepend("<li>在開頭添加列表項(xiàng)</li>"); }); }); </script> </head> <body> <p>段落。</p> <p>另一個(gè)段落。</p> <ol> <li>列表 1</li> <li>列表 2</li> <li>列表 3</li> </ol> <button id="btn1">添加文本</button> <button id="btn2">添加列表項(xiàng)</button> </body> </html>
append() 和 prepend() 方法能夠通過參數(shù)接收無限數(shù)量的新元素??梢酝ㄟ^ jQuery 來生成文本/HTML(就像上面的例子那樣),或者通過 JavaScript 代碼和 DOM 元素。
after() 和 before()?
jQuery after() 方法在被選元素之后插入內(nèi)容。
jQuery before() 方法在被選元素之前插入內(nèi)容。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("span").before("<b>之前</b>"); }); $("#btn2").click(function(){ $("span").after("<i>之后</i>"); }); }); </script> </head> <body> <span style="font-size: 30px;">內(nèi)容</span> <br><br> <button id="btn1">之前插入</button> <button id="btn2">之后插入</button> </body> </html>
after() 和 before() 方法能夠通過參數(shù)接收無限數(shù)量的新元素??梢酝ㄟ^ text/HTML、jQuery 或者 JavaScript/DOM 來創(chuàng)建新元素。