<JavaScript>节点删除(empty()与remove()方法)

一:empty()方法删除节点

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="../Jquery/jquery-3.3.1.js"></script>
    <style>
        div {
            background: #bbffaa;
            width: 300px;
            height: 200px;
        }
    </style>
</head>

<body>
<h2>通过empty移除元素</h2>
<div id="test">
    <p>p元素1</p>
    <p>p元素2</p>
</div>
<button>点击通过jQuery的empty移除元素</button>
<script type="text/javascript">
    /**
     * empty()只会清空该节点下的子 节点,但本身不会删除
     */
    $("button").on('click', function() {
        //通过empty移除了当前div元素下的所有p元素
        //但是本身id=test的div元素没有被删除!!!!!!
        $("#test").empty()
    })
</script>
</body>

</html>

二:remove方法删除

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="../Jquery/jquery-3.3.1.js"></script>
    <style>
        .test1 {
            background: #bbffaa;
        }

        .test2 {
            background: yellow;
        }
    </style>
</head>

<body>
<h2>通过jQuery remove方法移除元素</h2>
<div class="test1">
    <p>p元素1</p>
    <p>p元素2</p>
</div>
<div class="test2">
    <p>p元素3</p>
    <p>p元素4</p>
</div>
<button>通过点击jQuery的remove移除元素</button>
<button>通过点击jQuery的remove移除指定元素</button>
<script type="text/javascript">
    /**
     * 删除节点时需要把事件给销毁掉,这里是为了防止"内存泄漏"
     * remove内部会自动操作事件销毁方法
     **/
    $("button:first").on('click', function() {
        //删除整个 class=test1的div节点
        $(".test1").remove()
    })

    $("button:last").on('click', function() {
        //找到所有p元素中,包含了3的元素
        //这个也是一个过滤器的处理
        $("p").remove("p:contains('3')")//传入带参数的,可以散出指定元素
    })
</script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/lreing/p/9383551.html