把append()和prepnt()放一起理解,before()和after()放一起理解,两组分别都是给元素添加新元素的,我们以实例来说明它们之间的区别
append()和prepnt()
append()
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加列表项</button>
</body>
</html>
prepent()
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加列表项</button>
</body>
</html>
可以发现append()是给被选元素内部的结尾处添加新元素,prepend()是给被选元素内部的最前面添加
before()和after()
before()
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").before(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加列表项</button>
</body>
</html>
after()
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").after(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加列表项</button>
</body>
</html>
可以看出before()是给被选元素外部的前面添加,after()是给被选元素外部的后面添加的