首先来讲讲添加元素:
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是使该元素为空即只删除其子元素