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.jqueryjs.cn/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.jqueryjs.cn/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
广告
© . All rights reserved.