jQuery操作元素追加內容示例
阿新 • • 發佈:2020-01-11
本文例項講述了jQuery操作元素追加內容。分享給大家供大家參考,具體如下:
<html> <head> <title>jQuery操作文件結構</title> <meta charset="UTF-8"/> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> //內部的操作 function testAppend(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 showdiv.append("賽高"); //在物件內部的後面新增指定的內容,其是html可解析的內容,和html不同的是:html重新賦值(覆蓋)這個在內容後面追加 } function testAppend2(){ //獲取需要操作的物件 var u2=$("#u2"); //進行新增操作,指定內容的追加 // u2.appendTo("#show01"); //在物件的內部後面新增利用選擇器選擇的物件內容,把前面的物件移動到後面的物件的內部後面(一個剪下複製操作) $("#u2").appendTo(show01); } function testprepend(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 showdiv.prepend("<i>境界的彼方</i>"); //在物件的內部前面新增內容 } function testprependTo(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 $("#u2").prependTo(showdiv); //在物件的內部前面新增選擇器的物件(移動到) // showdiv.prependTo("#u2"); } //外部插入 function testAfter1(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 showdiv.after("もちろん"); //在物件的外部的後面新增內容 } function testAfter2(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 $("#u2").insertAfter(showdiv); //在物件的外部的後面新增選擇器的物件(移動到) // showdiv.prependTo("#u2"); } function testBefore1(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 showdiv.before("もちろん"); //在物件的外部的前面新增內容 } function testBefore2(){ //獲取需要操作的物件 var showdiv=$("#showdiv"); //進行新增操作,指定內容的追加 $("#u2").insertBefore(showdiv); //在物件的內部前面新增選擇器的物件 // showdiv.prependTo("#u2"); } </script> <style type="text/css"> #showdiv{ width: 300px; height: 300px; border: solid 1px; } #show01{ width: 300px; height: 300px; border: solid 1px; } </style> </head> <body> <h3>jQuery操作文件結構</h3> <h4>內部操作</h4> <input type="button" name="" id="" value="測試追加內容--append" onclick="testAppend()"/> <input type="button" name="" id="" value="測試移動內容--appendTo" onclick="testAppend2()"/> <input type="button" name="" id="" value="測試追加內容--prepend" onclick="testprepend()"/> <input type="button" name="" id="" value="測試移動內容--prependTo" onclick="testprependTo()"/> <hr /> <h4></h4> <input type="button" name="" id="" value="測試追加內容--after" onclick="testAfter1()"/> <input type="button" name="" id="" value="測試移動內容--after" onclick="testAfter2()"/> <input type="button" name="" id="" value="測試追加內容--before" onclick="testBefore1()"/> <input type="button" name="" id="" value="測試移動內容--before" onclick="testBefore2()"/> <hr /> <div id="showdiv"> <i>Clannad</i> </div><br /><br /> <div id="show01"> <!--<u>Clannad After Story</u>--> </div> <span id="u2"><u>Clannad After Story</u></span> <hr /> </body> </html>
感興趣的朋友可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。
更多關於jQuery相關內容感興趣的讀者可檢視本站專題:《jQuery頁面元素操作技巧彙總》、《jQuery常見事件用法與技巧總結》、《jQuery常用外掛及用法總結》、《jQuery擴充套件技巧總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程式設計有所幫助。