jQuery insertAfter()
使用jQuery after()和jQuery insertAfter()这两种方法来执行相同的任务,即在所选元素之后插入其他内容。
jQuery after()和insertAfter()之间的区别
after()和insertAfter之间的主要区别在于内容和目标的语法以及位置。
在after()方法中,目标是选定的元素,内容作为方法的参数放置。
$(target).after(contentToBeInserted)
在insertAfter()方法中,content是所选元素,而目标则作为该方法的参数放置。
$(contentToBeInserted).insertAfter(target)
注意:如果要在所选元素之前插入HTML元素,则应使用insertBefore()方法。
语法:
$(content).insertAfter(selector)
jQuery insertAfter()方法的参数
参数 |
说明 |
content |
这是强制性参数。它指定要插入的内容。 |
selector |
它也是必填参数。它指定插入内容的位置。> |
jQuery insertAfter()方法示例
我们来看一个jQuery insertAfter()方法示例。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<span><b>Hello lidihuo.com</b></span>").insertAfter("p");
});
});
</script>
</head>
<body>
<button>在每个p元素之后插入span元素</button>
<p>这是一个教程网站。</p>
<p>此是一家培训机构。</p>
</body>
</html>
输出:
这是一个教程网站。
此是一家培训机构。