jQuery replaceAll() 方法



jQuery 中的replaceAll() 方法用於將所有選定的元素替換為新的 HTML 元素。

此方法接受一個名為“selector”的引數,該引數指定要替換的元素。

語法

以下是 jQuery 中 replaceAll() 方法的語法:

$(content).replaceAll(selector)

引數

此方法接受以下引數:

  • content: 要插入的內容。可以是 HTML、jQuery 物件或 DOM 元素。
  • selector: 選擇器字串或 jQuery 物件,用於標識要替換的元素。

示例 1

在下面的示例中,我們使用 replaceAll() 方法將所有 <div> 元素替換為新的 <p> 元素:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $('<p>New Paragraph</p>').replaceAll('.old-paragraph');
            })
        });
    </script>
</head>
<body>
    <div class="old-paragraph">Old Paragraph 1</div>
    <div class="old-paragraph">Old Paragraph 2</div>
    <div class="old-paragraph">Old Paragraph 3</div>
    <button>Click to replace</button>
</body>
</html>

單擊按鈕時,所有 <div> 元素都將被新的 <p> 元素替換。

示例 2

在此示例中,我們將所有具有類“old-item”的“list”元素替換為新的列表項:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $('<li>New Item</li>').replaceAll('.old-item');
            })
        });
    </script>
</head>
<body>
    <ul>
        <li class="old-item">Old Item 1</li>
        <li class="old-item">Old Item 2</li>
        <li class="old-item">Old Item 3</li>
    </ul>
    <button>Click to replace</button>
</body>
</html>

執行上述程式後,選定的元素將被新的列表項替換。

jquery_ref_html.htm
廣告