本节教程介绍 before( ) 方法和 insertBefore( ) 方法在元素外部的“前面”插入内容。
在 jQuery 中,我们可以使用 before( ) 方法向所选元素外部的“前面”插入内容。
语法:
$(A).before(B) 表示往 A 外部的前面插入 B。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <style type="text/css">
- p{background-color:orange;}
- </style>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("#btn").click(function() {
- var $strong = "<strong>jQuery教程</strong>";
- $("p").before($strong);
- })
- })
- </script>
- </head>
- <body>
- <p>城东书院</p>
- <input id="btn" type="button" value="插入"/>
- </body>
- </html>
程序运行效果如图 1 所示。
我们点击【插入】按钮后,此时预览效果如图 2 所示。
我们点击【插入】按钮之后,此时得到的 HTML 结构如下。
- <strong>jQuery教程</strong><p>城东书院</p>
在 jQuery 中,insertBefore( ) 和 before( ) 这两个方法功能虽然相似,都是向所选元素外部的“前面”插入内容,但是两者的操作对象是颠倒的。
语法:
$(A).insertBefore(B) 表示将 A 插入到 B 外部的前面。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <style type="text/css">
- p{background-color:orange;}
- </style>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("#btn").click(function() {
- var $strong = "<strong>jQuery教程</strong>";
- $($strong).insertBefore("p");
- })
- })
- </script>
- </head>
- <body>
- <p>城东书院</p>
- <input id="btn" type="button" value="插入"/>
- </body>
- </html>
默认情况下,预览效果如图 3 所示。
我们点击【插入】按钮后,此时预览效果如图 4 所示。
在下面代码中,这两种插入节点的方式是等价的。
- //方式1
- var $strong = "<strong>jQuery入门教程</strong>";
- $("p").before($strong);
- //方式2
- var $strong = "<strong>jQuery入门教程</strong>";
- $($strong).insertBefore("p");