JQuery_添加&删除元素

本文深入讲解了jQuery中添加和删除元素的方法,包括append(), prepend(), after(), before(), remove()和empty()的用法及区别,通过实例展示了如何在网页元素的不同位置插入或移除内容。

首先来讲讲添加元素:
append()-在被选择元素的结尾插入内容
prepend()-在被选择元素的开头插入内容
after()-在被选元素之后插入内容
before()-在被选元素之前插入内容
相信看到这里的你,肯定疑问,那这append和after及prepend和before有啥区别呢?
其实很简单,就是是否还在同一元素内部,append和prepend插入的内容,仍然为该元素的一部分,而after和before所插入的内容,不属于该元素了,如下例子

<!DOCTYPE  html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$("#test1").click(function (){
$("p").append("<b>尾部加上元素<b>");
$("h").prepend("<i>在我的后面插入元素<i>");
});
});
</script>
<style>
p{
color:green;
background-color:yellow;
}
h{
color:blue;

}
</style>
</head>
<body>
<h>使用append方法在元素尾部插入元素</h>
<p>使用prepend方法在元素首部插入元素</p>
<button type="button"  id="test1">添加</button>
</body>
</html>

after&before如下例子

<!DOCTYPE  html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$("#test1").click(function (){
$("p").after("<b>尾部加上元素<b>");
$("h").before("<i>在我的后面插入元素<i>");
});
});
</script>
<style>
p{
color:green;
background-color:yellow;
}
h{
color:blue;
}
</style>
</head>
<body>
<h>使用after方法在元素之后插入元素</h>
<p>使用before方法在元素之前插入元素</p>
<button type="button"  id="test1">添加</button>
</body>
</html>

现象很明显,这两个方法,是不属于被选择元素的,所以其格式是不一样的。
接下来就看看删除:
主要有两个删除方法
remove() 删除元素及其子元素,就和linux上一样删除目录,连子目录也一块删除掉
empty()将被选元素的子元素删除掉,留下被选中的父元素

<!DOCTYPE  html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$("#test1").click(function (){
$("#c2").remove();
$("#cc").empty();
});
});
</script>
<style>
#cc{
color:green;
background-color:yellow;
	border:10px solid #aa1;
	width:200px;
		height:200px;
}
#c2{
color:blue;
background-color:red;
border:10px solid #cd4;
	width:200px;
	height:200px;
	
}
</style>
</head>
<body>
<div id="cc"><h>使用remove方法删除元素,其本身和子元素会被一并删除</h><br />
	<h>使用remove方法删除元素,其本身和子元素会被一并删除</h><br />
	<h>使用remove方法删除元素,其本身和子元素会被一并删除</h><br /></div>
<div id="c2"><p>使用empty空,只删除子元素,使其本身变空</p>
	<p>使用empty空,只删除子元素,使其本身变空</p>
	<p>使用empty空,只删除子元素,使其本身变空</p>
</div>
	
<button type="button"  id="test1">删除</button>
</body>
</html>

通过这个程序可以很清楚看到,remove是将被选元素和子元素都删除,而empty是使该元素为空即只删除其子元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值