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.jquery.com/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.jquery.com/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.jquery.com/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.