这个方法跟prependTo()和appendTo()不一样的地方在于,一个是仍然插入到元素内部,而insertAfter和insertBefore是插入到元素外部。
这里拿insertBefore来作为例子说一下:
使用方法:
第一种方法:插入代码:
<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){ ?$("button").click(function(){ ???$("<span>你好!</span>").insertAfter("p"); ?});});</script></head><body><p>这是一个段落。</p><p>这是另一个段落。</p><button>在每个 p 元素之后插入 span 元素</button></body></html>
插入前:
插入后:
第二种方法:插入已有的元素
会把已有的元素取出来,插入到特定元素的指定位置。
<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){ ?$("button").click(function(){ ?? $("h1").insertAfter("p"); ?});});</script></head><body><h1>这是一个标题</h1><p>这是一个段落。</p><p>这是另一个段落。</p><button>在每个 p 元素之后插入 h1 元素</button></body></html>
插入前:
插入后:
会发现,已有的元素在原来的位置消失了,而被复制,插入到特定位置上了。
jQuery 文档操作 - insertAfter() ,insertBefore() 方法
原文地址:http://www.cnblogs.com/alsf/p/7640520.html