jQuery before()方法

jQuery before()方法

jQuery中的before()方法是用来在选定的元素之前添加内容。

语法:

$(selector).before( content, function(index) )

参数:该方法接受上面提到的和下面描述的两个参数。

  • content。这个参数持有要插入元素之前的内容。内容的可能值可以是HTML元素,DOM元素,jQuery元素。
  • function(index)。它是一个可选的参数,用于指定一个函数,返回要在元素前插入的内容,而索引则返回元素的索引定位。

例子1:这个例子在元素之前插入了内容。

<!DOCTYPE html>
<html>
 
<head>
    <title>
        jQuery before() Method
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
 
    <!-- Script to insert element before button element -->
    <script>
        (document).ready(function () {
            ("button").click(function () {
                $("button").before("<p>GeeksforGeeks:"
                    + " A computer science portal</p>");
            });
        });
    </script>
</head>
 
<body>
    <button>
        Click Here to Insert element before button
    </button>
</body>
 
</html>

输出:

jQuery before()方法

例子2:这个例子在指定元素之前插入内容。

<!DOCTYPE html>
<html>
 
<head>
    <title>
        jQuery before() Method
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
 
    <!-- Script to add content before the element -->
    <script>
        (document).ready(function () {
            ("button").click(function () {
                $("span").before("<span>GeeksforGeeks: </span>");
            });
        });
    </script>
</head>
 
<body>
    <span>A computer science portal for geek</span><br>
    <span>A computer science portal for geek</span><br>
    <span>A computer science portal for geek</span><br>
    <button>Click to insert</button>
</body>
 
</html>

输出:

jQuery before()方法

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程