16-6元素的删除与内容清空操作:remove() empty()

16-6元素的删除与内容清空操作:remove() empty()

科底懦烧喜程菏书写扫吩写趴


初始结构:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			li
			{
				width:300px;
			}
			.hot
			{
				background-color:lightgreen;
			}
			.top
			{
				background-color:yellow;
			}
		</style>
	</head>
	<body>
		<ul>
			<li><a href="">萌面人资料铺01</a></li>
			<li><a href="">萌面人资料铺02</a></li>
			<li class="hot"><a href="">萌面人资料铺03</a></li>
			<li class="hot"><a href="">萌面人资料铺04</a></li>
			<li class="hot"><a href="">萌面人资料铺05</a></li>
			<li><a href="">萌面人资料铺06</a></li>
			<li><a href="">萌面人资料铺07</a></li>
			<li class="top"><a href="">萌面人资料铺08</a></li>
			<li class="top"><a href="">萌面人资料铺09</a></li>
			<li class="top"><a href="">萌面人资料铺10</a></li>
		</ul>
		<button>remove()删除绿色背景元素</button>
		<button>empty()清空黄色背景元素的内容</button>
	</body>
</html>

执行:

16-6元素的删除与内容清空操作:remove() empty()第1张


/**
* 1. remove(): 删除元素
* 参数: 选择器
*/
删除绿色背景元素

js代码:

<script type="text/javascript" src="../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">
	$('button').eq(0).on('click',function(){
		$('li').filter('.hot').remove()
	})
</script>

执行,点击第一个按钮,成功删除元素:

16-6元素的删除与内容清空操作:remove() empty()第2张

也可以将删除条件写到remove()方法参数中,这样可简化语句

<script type="text/javascript" src="../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">
	$('button').eq(0).on('click',function(){
		$('li').remove('.hot')	
	})
</script>


/**
* 2. empty()
* 参数: 无
* 功能: 清空元素的内容,在Ajax调用时使用最多
*/
清空黄色背景颜色的内容

<script type="text/javascript" src="../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">
	$('button').eq(0).next().on('click',function(){
		$('li').filter('.top').empty()
	})
</script>

执行,点击第二个按钮

16-6元素的删除与内容清空操作:remove() empty()第3张


函醛屡寿撂习露南趟舱谭闯凑