批改状态:合格
老师批语:
演示地址:http://111.231.88.20/front/html/0408/1.html
代码使用appendTo()、perpendTo()、insertAfter()、insertBefore()演示了对页面内元素的添加和移动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>0408作业添加或移动元素到目标节点</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<button>appendTo()的添加操作</button>
<button>appendTo()的移动操作</button>
<button>prependTo()的添加操作</button>
<button>prependTo()的移动操作</button>
<button>insertAfter()的添加操作</button>
<button>insertAfter()的移动操作</button>
<button>insertBefore()的添加操作</button>
<button>insertBefore()的移动操作</button>
<p style="background-color: orangered; width: 300px;">appendTo()移动节点</p>
<p style="background-color: lightgreen; width: 300px;">prependTo()移动节点</p>
<p style="background-color: lightblue; width: 300px;">insertAfter()移动节点</p>
<p style="background-color: lightcoral; width: 300px;">insertBefore()移动节点</p>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
//使用appendTo()添加一个新元素
$('button').eq(0).on('click',function(){
$('<li>')//创建一个li标签
.text('appendTo()添加元素')//添加文本内容
.width('300px')//设置元素宽度
.css('background-color','orangered')//设置元素样式
.appendTo($('ul'))//添加到ul标签内容的最后面
})
//使用appendTo()将页面中已有的元素进行移动
$('button').eq(1).on('click',function(){
$('p:first').appendTo($('ul'))
})
//使用prependTo()添加一个新元素
$('button').eq(2).on('click',function(){
$('<li>')//创建一个li标签
.text('prependTo()添加元素')//添加文本内容
.width('300px')//设置元素宽度
.css('background-color','lightgreen')//设置元素样式
.prependTo($('ul'))//添加到ul标签内容的最前面
})
//使用prependTo()将页面中已有的元素进行移动
$('button').eq(3).on('click',function(){
$('p').eq(1).prependTo($('ul'))
})
//使用insertAfter()添加一个元素到指定位置
$('button').eq(4).on('click',function(){
$('<li>')//创建一个li标签
.text('insertAfter()添加元素')//添加文本内容
.width('300px')//设置元素宽度
.css('background-color','lightblue')//设置元素样式
.insertAfter($('li:eq(0)'))//添加到第一个li标签的后面
})
//使用insertAfter()将页面中已有的元素进行移动
$('button').eq(5).on('click',function(){
$('p').eq(2).insertAfter($('li:eq(2)'))
})
//使用insertBefore()添加一个元素到指定位置
$('button').eq(6).on('click',function(){
$('<li>')//创建一个li标签
.text('insertBefore()添加元素')//添加文本内容
.width('300px')//设置元素宽度
.css('background-color','lightcoral')//设置元素样式
.insertBefore($('li:eq(3)'))//添加到第四个li标签的前面
})
//使用insertBefoer()将页面中已有的元素进行移动
$('button').eq(7).on('click',function(){
$('p').eq(3).insertBefore($('li:eq(4)'))
})
</script>
</html>点击 "运行实例" 按钮查看在线实例
原始效果图

依次点击按钮以后

总结:
appendTo()添加新元素和移动已有元素的时候是添加在指定元素内容的最后面
prependTo()添加新元素和移动已有元素的时候是添加在指定元素内容的最前面
insertAfter()添加新元素和移动已有元素的时候是添加在指定元素的后面
insertBefore()添加新元素和移动已有元素的时候是添加在指定元素的前面
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号