jQuery .empty() 详细讲解

.empty()

摘要

    Categories: Manipulation > DOM Removal

    Version added: 1.0.empty()

    DescriptionRemove all child nodes of the set of matched elements from the DOM.

    Extra: This method does not accept any arguments

 

用法

    This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

    We can target any element for removal:

	
$( ".hello" ).empty();

    This will result in a DOM structure with the Hello text deleted:

<div class="container">
  <div class="hello"></div>
  <div class="goodbye">Goodbye</div>
</div>

    If we had any number of nested elements inside <div class="hello">, they would be removed, too.

    To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

    If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach()instead.

示例

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>empty demo</title>
  <style>
  p {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<p>
  Hello, <span>Person</span> <em>and person</em>.
</p>
 
<button>Call empty() on above paragraph</button>
 
<script>
$( "button" ).click(function() {
  $( "p" ).empty();
});
</script>
 
</body>
</html>
104854_DkpQ_1864705.png

转载于:https://my.oschina.net/leblancs/blog/790677

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值