jQuery-文檔處理1append-appendTo-prepend-prependTo-after-before的應用,jqueryappendto
<!doctype html><html><head><meta charset="gb2312"><title>buzhang-title</title><script src="js/jquery-1.11.1.min.js"></script><script>$(document).ready(function(e) { //$('p').append('<b>hello</b>'); //$('p').appendTo('div');//向每個匹配的元素內部前置內容。 //這是向所有匹配元素內部的開始處插入內容的最佳方式。 //$("p").prepend("<b>Hello</b>");//把所有匹配的元素前置到另一個、指定的元素元素集合中。 //實際上,使用這個方法是顛倒了常規的$(A).prepend(B)的操作,即不是把B前置到A中,而是把A前置到B中。 //$("p").prependTo("#foo"); //結果:<div id="foo"><p>I would like to say: </p></div> //appendTo把所有匹配的元素追加到另一個指定的元素元素集合中。 //$('<b>aaaaaaa<b>').appendTo('p');//after在每個匹配的元素之後插入內容。 //$('div').after('-aaa');//before在每個匹配的元素之前插入內容。 //$('div').before('aaa-');//append向每個匹配的元素內部追加內容。 $('body').append('<div>ok</div>');});</script></head><body><p>p1</p><hr><p>p2</p><p>I would like to say: </p><hr><div></div><hr><p>I would like to say: </p><div id="foo"></div><hr><div>aaaaaaaaaa<b>hhhhhhhhh</b></div>ok</body></html>
jquery 文檔處理事件的不同點
append() 向匹配的元素內部追加內容。
appendTo() 向匹配的元素內部追加內容。
before() 在每個匹配的元素之前插入內容。
insertAfter() 把匹配的元素插入到另一個指定的元素集合的後面。
insertBefore() 把匹配的元素插入到另一個指定的元素集合的前面。
prepend() 向每個匹配的元素內部前置內容。
prependTo() 向每個匹配的元素內部前置內容。
Jquery 文檔處理
w3school 對 jQuery .append( Function function(index, html) ) 的簡單解釋:
規定返回待插入內容的函數。index 為接收選取器的 index 位置。html 為接收選取器的當前 HTML。
但是我覺得還是上代碼比較直觀一些:
<script type="text/javascript">$(function() { // 尋找所有 div $("div").append(function(index, html) { // 根據 index 判斷 switch(index) { // 第一個(0) div 後面 append "度" 字 case 0: html += "度"; break; // 第二個(1) div 後面 append "歌" 字 case 1: html += "歌"; break; // 第三個(2) div 後面 append "虎" 字 case 2: html += "虎"; break; } // 設定 HTML $(this).html(html); });});</script> <div>百</div><div>穀</div><div>雅</div>
代碼運行後得到的結果就是
<div>百度</div><div>Google</div><div>雅虎</div>