博客列表 >JQ学习-appendTo(),prependTo(),insertAfter(),insertBefore()方法使用20180410

JQ学习-appendTo(),prependTo(),insertAfter(),insertBefore()方法使用20180410

MrZ的博客
MrZ的博客原创
2018年04月10日 11:30:05707浏览

一、学习心得

1,元素添加及移动方法学习。

2,该方法主要是移动或添加元素到目标节点。

3,使用好处,能实现链式操作,减少代码冗余,更清晰整洁。

二、演示截图

QQ截图20180410112941.png

三、代码部分(每种方法详细说明)

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>appendTo(),prependTo(),insertAfter(),insertBefore()方法说明</title>
</head>
<style type="text/css">
	li{
		background-color: red;
		width: 200px;
		margin-bottom: 10px;
	}
</style>
<body>
	<ul>
		<li>第一个列表项</li>
		<li>第二个列表项</li>
		<li>第三个列表项</li>
		<li>第四个列表项</li>
	</ul>
	<button>方法1</button>
	<!-- appendTo() -->

	<button>方法2</button>
	<!-- prependTo() -->

	<button>方法3</button>
	<!-- insertAfter() -->

	<button>方法4</button>
	<!-- insertBefore() -->

	<p style="background-color: green;width: 200px ;color: white" >appendTo()方法的移动节点</p>
	<p style="background-color: green;width: 200px ;color: white">prependTo()方法的移动节点</p>
	<p style="background-color: green;width: 200px ;color: white">insertAfter()方法的移动节点</p>
	<p style="background-color: green;width: 200px ;color: white">insertBefore()方法的移动节点</p>

</body>

<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">

	$('button').eq(0).on('click',function(){
// appendTo()方法的添加节点
		var li=$('<li>').text('添加的标签1').css('background-color','blue')

		li.appendTo($('ul'))

// appendTo()方法移动节点
		$('p:first').appendTo($('ul'))


	}

		);


	$('button').eq(1).on('click',function(){
// prependTo()方法的添加节点
		var li=$('<li>').text('添加的标签2').css('background-color','blue')

		li.prependTo($('ul'))

 // prependTo()方法移动节点
		$('p:eq(1)').prependTo($('ul'))


	}

		);


	$('button').eq(2).on('click',function(){
// insertAfter()方法的添加节点
		var li=$('<li>').text('添加的标签3').css('background-color','blue')

		li.insertAfter($('ul'))

 // insertAfter()方法移动节点
	$('p:eq(2)').insertAfter($('ul'))


	}

		);


	$('button').eq(3).on('click',function(){
// insertBefore()方法的添加节点
		var li=$('<li>').text('添加的标签4').css('background-color','blue')

		li.insertBefore($('ul'))

 // insertBefore()方法移动节点
	$('p:eq(3)').insertBefore($('ul'))


	}

		);


</script>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议