jQuery replaceWith()的例子

jQuery replaceWith()的例子

replaceWith()方法是jQuery内置的一个方法,用于用新的元素替换选定的元素。

语法:

$(selector).replaceWith(content, function)

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

  • content。这是一个必要参数,用于指定需要替换的内容。
  • para2:这是一个可选的参数,在调用后执行。

返回值:该方法返回有变化的选定元素。

下面的代码说明了jQuery中的replaceWith()方法。

示例 1:

<!DOCTYPE html>
<html>
    <head>
        <title>The replaceWith method</title>
        <script src=
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
        <style>
            button {
                display: block;
                margin: 10px;
                color: red;
                width: 200px;
                padding: 3px;
            }
            div {
                color: green;
                border: 2px solid green;
                width: 200px;
                margin: 3px;
                padding: 5px;
                font-size: 20px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <!-- click on individual button and see the change -->
        <button>Geeks</button>
        <button>for</button>
        <button>Geeks</button>
          
        <!-- jQuery code to show the working of this method -->
        <script>
            ("button").click(function() {
                (this).replaceWith("<div>" + $(this).text() + "</div>");
            });
        </script>
    </body>
</html>

输出:
在点击任何按钮之前。
jQuery replaceWith()的例子
点击所有按钮后。
jQuery replaceWith()的例子

例子2:在下面的代码中,传递了可选函数。

<!DOCTYPE html>
<html>
    <head>
        <title>The replaceWith method</title>
        <script src=
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
        <style>
            button {
                display: block;
                margin: 4px;
                color: green;
                width: 150px;
                padding: 5px;
            }
            div {
                width: 200px;
                height: 100px;
                padding: 20px;
                border: 2px solid green;
            }
        </style>
    </head>
    <body>
        <div>
            <p>Welcome to </p>
              
            <!-- click on this button and see the change -->
            <button>Click Here!</button>
        </div>
          
        <!-- jQuery code to show the working of this method -->
        <script>
            var x = "GeeksforGeeks!";
            ("button").click(function() {
                ("p").replaceWith(x).replaceWith(function(n) {
                    alert("Click ok and string will replace");
                    return n;
                });
            });
        </script>
    </body>
</html>

输出:
jQuery replaceWith()的例子

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程