使用Jquery在UL中添加或删除指定LI元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31490071/article/details/83309088

今天看了很多帖子,对于元素的添加和删除的方法都很多,但我的要求就是用最简单的代码实现功能,不喜欢太复杂的内容,所以通过自己的实践,写了一个简单的demo,直接上代码,为下一个项目做准备

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="心若向阳">
<title>心若向阳无谓悲伤</title>
<style type="text/css">
	.item{
		background: #C0C0C0;
		border-radius: 20px;
		margin-bottom: 10px;
		height:40px;
		padding-left: 20px;
		color:white;
		font-family: "微软雅黑";
		text-align: center;
		padding-top: 15px;
	}
	#content{
		list-style: none;
	}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$ (function ()
{
$ ('#add').click (function ()
{
	if($("#content").children().length >=5){
		alert("最多允许添加5个")
		return;
	}
$('#content').append('<li class="item" >'+$("#content").children().length+'</li>');
});

$ ('#delete').click (function ()
{
	var len = $("#content").children().length-1;
	if(len >=0){
	 $("ul li:eq("+len+")").remove();  //表示删除最后一个元素
	}else{
		alert("还没有添加元素哦");
	}
	

});
})

</script>
</head>
<body>
	<div >
		<ul id="content">
			
		</ul>
	</div>
<button id="add">添加div</button>
<button id="delete">删除div</button>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_31490071/article/details/83309088