批改狀態(tài):合格
老師批語:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="../jquery/jquery-3.2.1.min.js"></script> <title>jQuery將節(jié)點(diǎn)添加或移動(dòng)到目標(biāo)節(jié)點(diǎn)</title> <style> li { background-color: lightskyblue; margin-bottom: 5px; } button { color: black; background-color: white; } p { background-color: lightsalmon; } </style> </head> <body> <ul> <li>列表項(xiàng)1</li> <li>列表項(xiàng)2</li> <li>列表項(xiàng)3</li> <li>列表項(xiàng)4</li> </ul> <button>appendTo()</button> <button>prependTo()</button> <button>insertAfter()</button> <button>insertBefore()</button> <p>我是insertAfter()的移動(dòng)節(jié)點(diǎn)</p> <p>我是insertBefore()的移動(dòng)節(jié)點(diǎn)</p> <p>我是移動(dòng)節(jié)點(diǎn)</p> </body> <script> $('button:eq(0)').on('click',function () { //1.創(chuàng)建一個(gè)新節(jié)點(diǎn) var tem1=$('<li>').css('background','#696969').text('我被添加到列表內(nèi)容最后的,請(qǐng)Q1') tem1.appendTo('ul')//將新節(jié)點(diǎn)添加到指定位置 // 2.對(duì)頁面中已經(jīng)存在的節(jié)點(diǎn)進(jìn)行移動(dòng)操作 $('p:eq(2)').appendTo($('li:eq(2)')) }) $('button:eq(1)').on('click',function () { var tem2=$('<li>').css('background','#696969').text('我被添加到列表內(nèi)容最前的,請(qǐng)Q2') tem2.prependTo('ul') // 2.對(duì)頁面中已經(jīng)存在的節(jié)點(diǎn)進(jìn)行移動(dòng)操作 $('p:eq(2)').prependTo($('li:eq(2)')) }) $('button:eq(2)').on('click',function () { var tem3=$('<p>').css('background','yellow').text('這個(gè)方法,比插到列表內(nèi)容的位置還要后,無語啦~~') tem3.insertAfter('ul') // 2.對(duì)頁面中已經(jīng)存在的節(jié)點(diǎn)進(jìn)行移動(dòng)操作 $('p:eq(2)').insertAfter($('li:eq(2)')) }) $('button:eq(3)').on('click',function () { var tem4=$('<p>').css('background','yellow').text('終于搶到列表最前面了,好開森~~~~~') tem4.insertBefore('ul') // 2.對(duì)頁面中已經(jīng)存在的節(jié)點(diǎn)進(jìn)行移動(dòng)操作 $('p:eq(2)').insertBefore($('li:eq(2)')) }) </script> </html>
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
總結(jié):
appendTo(content),prependTo(content)是將節(jié)點(diǎn)添加到目標(biāo)節(jié)點(diǎn)的內(nèi)容之后和之前
insertAfter(),insertBefore()將節(jié)點(diǎn)插入到目標(biāo)節(jié)點(diǎn)之后和之前
返回值都是jQuery類型,返回當(dāng)前jQuery對(duì)象本身
運(yùn)行效果圖:
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)