jQuery操作文档结构
一、内部插入
1、append(“内容”)
将指定的内容追加到对象的内部
function testAppend(){
//获取元素对象
var div = $("#showdiv");
//使用内部插入
div.append("<i>内部插入的香肠</i>")
}
2、appendTo(元素对象或者选择器)
将指定的元素对象追加到指定的对象内容
function testAppendTo(){
//获取元素对象
var div = $("#showdiv");
//使用appendTo()
$("#ul").appendTo(div);
}
3、prepend()
将指定的内容追加到对象的内部的前面
function testPrepend(){
//获取元素
var div=$("#showdiv");
//使用prepend()
div.prepend("<i>放在前面的鸡翅</i>");
}
4、prependTo()
$(内容).prependTo(目标元素) 把内容插入到…内部的首端
function testPrepend(){
//获取元素
var div=$("#showdiv");
//使用prepend()
$("<i>放在前面的鸡翅</i>").prependTo(div);
}
二、外部插入
1、after
将指定的内容追加到指定的元素后面
function testAfter(){
//获取元素对象
var div = $("#showdiv");
//使用after外部插入
div.after("<b>使用after的外部插入的汉堡包</b>");
}
2、before
将指定的内容追加到指定的元素前面
function testBefore(){
//获取元素对象
var div = $("#showdiv");
//使用before的外部插入
div.before("<b>使用before的外部插入的汉堡包</b>")
}
3、insertAfter
把所有匹配的元素插入到另一个,指定的元素元素集合的后面
//获取元素对象
var div = $("#showdiv");
div.click(function () {
$("<b>吃饭</b>").insertAfter('.bag');
});
4、insertBefore
把所有匹配的元素插入到另一个,指定的元素元素集合的前面
insertBefore(newnode,node);
5、清空内容
function testEmpty(){
$("#showdiv").empty();
}
三、完整代码
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width = device - width, initial - scale = 1.0">
<meta http-equiv = "X-UA-Compatible" content = "ie-edge">
<title>jQuery操作文档结构</title>
<style type="text/css">
#showdiv{
width:300px;
height:300px;
border:solid 3px orange;
}
</style>
<script src="js/jQuery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//内部插入
function testAppend(){
//获取元素对象
var div = $("#showdiv");
//使用内部插入
div.append("<i>内部插入的香肠</i>")
}
function testAppendTo(){
//获取元素对象
var div = $("#showdiv");
//使用appendTo()
$("#ul").appendTo(div);
}
function testPrepend(){
//获取元素
var div=$("#showdiv");
//使用prepend()
div.prepend("<i>放在前面的鸡翅</i>");
//$("<i>放在前面的鸡翅</i>").prependTo(div);
}
function testAfter(){
//获取元素对象
var div = $("#showdiv");
//使用after外部插入
div.after("<b>使用after的外部插入的汉堡包</b>");
}
function testBefore(){
//获取元素对象
var div = $("#showdiv");
//使用before的外部插入
div.before("<b>使用before的外部插入的汉堡包</b>")
}
function testEmpty(){
$("#showdiv").empty();
}
</script>
</head>
<body>
<h3>jQuery操作文档结构</h3>
<input type="button" name="" id="" value="操作append()" onclick="testAppend()"/>
<input type="button" name="" id="" value="操作append()" onclick="testAppendTo()"/>
<input type="button" name="" id="" value="操作Prepend()" onclick="testPrepend()"/>
<hr/>
<input type="button" name="" id="" value="操作After()" onclick="testAfter()"/>
<input type="button" name="" id="" value="操作Before()" onclick="testBefore()"/>
<input type="button" name="" id="" value="测试empty" onclick="testEmpty()"/>
<hr/>
<u id="ul">每天下午都是充斥着面包浓浓的香味</u>
<div id="showdiv" class="bag">
<b>西红柿</b>
</div>
</body>
</html>