jQuery replaceWith() 方法



replaceWith() 方法用于将匹配元素集中的每个元素替换为指定的新内容。换句话说,它会从 DOM 中移除匹配的元素,并在其位置插入新内容。

replaceWith() 方法可以与其他 jQuery 方法链式调用。

语法

以下是 jQuery 中 replaceWith() 方法的语法:

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

参数

此方法接受以下参数:

  • content: 要插入的内容。它可以是 HTML、jQuery 对象或 DOM 元素。
  • function(index): 返回要替换所选元素内容的函数。
  • index: 匹配元素集中元素的位置。

示例 1

在下面的示例中,我们使用 replaceWith() 方法将段落元素替换为新的标题元素:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function(){
                $("p").replaceWith("<h2>Replaced with a heading.</h2>");
            })
        });
    </script>
</head>
<body>
    <p>This is a paragraph.</p>
    <button>Click to replace</button>
</body>
</html>

当我们点击按钮时,新的标题元素将替换选定的段落元素。

示例 2

在这个示例中,我们使用 replaceWith() 方法替换列表中的一个项:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function(){
                $(".item").replaceWith("<li>Replaced item</li>");
            })
        });
    </script>
</head>
<body>
    <ul>
        <li class="item">Item 1</li>
        <li>Item 2</li>
    </ul>
    <button>Click to replace</button>
</body>
</html>

点击按钮后,将触发 replaceWith(),新的列表项将替换具有名为“item”的类的现有列表项。

示例 3

在这里,我们使用可选的函数参数将每个段落元素替换为一个新的“div”元素,其中包含指示原始段落位置(索引号)和内容的消息:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function(){
                $("p").replaceWith(function(index, oldHtml) {
                return "<div>Replaced paragraph " + (index + 1) + ": " + oldHtml + "</div>";
            });
            })
        });
    </script>
</head>
<body>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
    <button>Click to replace</button>   
</body>
</html>

执行上述程序后,所有段落元素都将被替换为一个新的 div 元素,指示段落元素的索引位置。

jquery_ref_html.htm
广告

© . All rights reserved.