DOM节点删除之empty()的基本用法

来源:互联网 发布:超级电容给单片机供电 编辑:程序博客网 时间:2024/06/18 13:06

empty 顾名思义,清空方法,但是与删除又有点不一样,因为它只移除了 指定元素中的所有子节点。
这个方法不仅移除子元素(和其他后代元素),同样移除元素里的文本。因为,根据说明,元素里任何文本字符串都被看做是该元素的子节点。请看下面的HTML:

<div class="hello"><p>慕课网</p></div>

如果我们通过empty方法移除里面div的所有元素,它只是清空内部的html代码,但是标记仍然留在DOM中

//通过empty处理$('.hello').empty()//结果:<p>慕课网</p>被移除<div class="hello"></div>
<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>    <style>    div {        background: #bbffaa;        width: 300px;    }    </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">    $("button").on('click', function() {        //通过empty移除了当前div元素下的所有p元素        //但是本身id=test的div元素没有被删除        $("#test").empty()    })    </script></body></html>

这里写图片描述

原创粉丝点击