jQuery(五)remove()、empty()

remove():方法移除被选元素,包括所有的文本和子节点。
该方法也会移除被选元素的数据和事件。
提示:如需移除元素,但保留数据和事件,请使用 detach() 方法代替。
如只需从被选元素移除内容,请使用 empty() 方法。

empty(): 方法从被选元素所有子节点和内容。
该方法不会移除元素本身,或它的属性。
如需移除元素及它的数据和事件,请使用 remove() 方法。
示列:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="../js/jquery.js" type="text/javascript"></script>
  <style type="text/css">
    .max {
      width: 300px;
      height: 400px;
      border: 1px solid rebeccapurple;
      margin: 0 auto;
      text-align: center;
    }

    p {
      display: none;
    }

    .box {
      width: 150px;
      height: 20px;
      margin: 0 auto;
    }
  </style>

</head>

<body>
  <script type="text/javascript">
    $(function () {
      $('#a').on('click', function () {
        var s = document.createElement('h1');
        var s1 = document.createTextNode('hello world');
        $('.max').append(s);
        s.append(s1);
      })
      $('#b').on('click', function () {
        $('h1:eq(0)').detach();
      })
      $('#c').on('click', function () {
        $('.max').empty();
      })
      $('#d').on('click', function () {
        $('.max').remove();
      })
    })
  </script>
  <div class="max">
    <input type="button" id="a" value="添加">
    <input type="button" id="b" value="删除">
  </div>
  <p>hello world</p>
  <br/>
  <div class="box">
    <input type="button" id="c" value="删除样式">
    <input type="button" id="d" value="清空">
  </div>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_38904347/article/details/82859769
今日推荐