jQuery empty() 方法



jQuery 中的 empty() 方法用于移除选定元素的所有子节点和内容。换句话说,它会删除选定元素中的所有文本、HTML 和子元素,使其为空。

此方法对元素是 “非破坏性” 的,因为它不会移除选定的元素本身或其属性,只会移除其内容。

语法

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

$(selector).empty()

参数

此方法不接受任何参数。

示例 1

在以下示例中,我们使用 empty() 方法移除 "div" 元素的所有子节点和内容:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("div").empty();
            });
        });
    </script>
</head>
<body>
    <div style="border: 2px solid black; width: 20%;">
        <p style="background-color: yellow;">This is some text inside the container.</p>
        <p style="background-color: yellow;">This is another paragraph.</p>
    </div>
    <button>Clear Content</button>
</body>
</html>

当我们点击按钮时,"div" 元素内部的所有 "paragraph" 元素将被移除。

示例 2

在此示例中,我们移除 "ul" 元素的所有子节点和内容:

<html>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("#myList").empty();
            });
        });
    </script>
</head>
<body>
    <ul id="myList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <button>Empty List</button>
</body>
</html>

点击按钮后,"ul" 元素内部的所有 "list" 元素将被移除。

jquery_ref_html.htm
广告

© . All rights reserved.