1.append ()
向每个匹配的元素内部追加内容。
实例:
<div style="background-color: #222222;color: white" >
<p id="p1">first</p>
<p id="p2">second</p>
<p id="p3">third</p>
<div style="background-color: #666677" id="div">
<a href="index.html" style="background-color: #35b558">jump to</a>
</div>
<button id="btn">button</button>
</div>
效果:
第一段jQuery
$("#btn").click(function(){
$("#div a").append($("#p1"));
})
效果
实际形成的HTML代码:
<div style="background-color: #222222;color: white" >
<p id="p2">second</p>
<p id="p3">third</p>
<div style="background-color: #666677" id="div">
<a href="index.html" style="background-color: #35b558">jump to
<p id="p1">first</p>
</a>
</div>
<button id="btn">button</button>
</div>
第二段jQuery代码
$("#btn").click(function(){
$("#div").append("<b>hello world</b>");
})
效果:
实际形成的HTML代码
<div style="background-color: #222222;color: white" >
<p id="p1">first</p>
<p id="p2">second</p>
<p id="p3">third</p>
<div style="background-color: #666677" id="div">
<a href="index.html" style="background-color: #35b558">jump to</a>
<b>hello world</b>
</div>
<button id="btn">button</button>
</div>
2.prepend()
向每个匹配的元素内部前置内容。
实现起来与append()是一致的,只是每次在元素前面插入
例如同样的jQuery代码:
$("#btn").click(function(){
$("#div").append("<b>hello world</b>");
})
实际形成的HTML代码
<div style="background-color: #222222;color: white" >
<p id="p1">first</p>
<p id="p2">second</p>
<p id="p3">third</p>
<div style="background-color: #666677" id="div">
<b>hello world</b>
<a href="index.html" style="background-color: #35b558">jump to</a>
</div>
<button id="btn">button</button>
</div>
3.appendTo()
把所有匹配的元素追加到另一个指定的元素元素集合中。
实际上,使用这个方法是颠倒了常规的$(A).append(B)的操作,即不是把B追加到A中,而是把A追加到B中。
$("#btn").click(function(){
$("#div").appendTo("#p1");
})
效果:
实际形成的HTML代码:
<div style="background-color: #222222;color: white" >
<p id="p1">first
<div style="background-color: #666677" id="div">
<a href="index.html" style="background-color: #35b558">jump to</a>
</div>
</p>
<p id="p2">second</p>
<p id="p3">third</p〉
<button id="btn">button</button>
</div>
4. prependTo()
把所有匹配的元素前置到另一个、指定的元素元素集合中。