jQuery insertBefore()实例

jQuery insertBefore()实例

insertBefore()是jQuery内置的一个方法,用于在一个指定的元素之前插入一些HTML内容。HTML内容将被插入到指定元素的每次出现之前。

语法:

$(content).insertBefore(target)

这里的内容是需要插入到指定目标之前的HTML内容。
参数:它接受一个参数 “target”,这是内容要插入的目标。
返回类型:它不返回任何值。
jQuery代码显示insertBefore()方法的工作:
代码 #1:

<!DOCTYPE html>
<html>
  
<head>
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        (document).ready(function() {
            ("div").click(function() {
                // insertBefore
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p");
            });
        });
    </script>
</head>
  
<body>
  
    <p>To learn jQuery </p>
  
    <div>Click here to complete</div>
  
</body>
  
</html>

输出:
在点击div content-

To learn jQuery
Click here to complete

在点击了div content-

You should follow GeeksForGeeks
To learn jQuery 
Click here to complete

代码 #2:

<!DOCTYPE html>
<html>
  
<head>
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        (document).ready(function() {
            ("div").click(function() {
                // insertBefore
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p");
            });
        });
    </script>
</head>
  
<body>
  
    <p>To learn jQuery </p>
  
    <p> To learn coding </p>
  
    <div>Click here to complete</div>
  
</body>
  
</html>

输出:
在点击div content-

To learn jQuery 
To learn coding 
Click here to complete

在点击了div content-

You should follow GeeksForGeeks
To learn jQuery 
You should follow GeeksForGeeks
To learn coding
Click here to complete

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程