事件委托实现关闭模块

HTML:  container中有三个pane,点击按钮pane会消失

<div id="container">
    <div class="pane">
      <h3>Horse</h3>
      <p>The horse is one of two extant subspecies of Equus ferus. It is an odd-toed ungulate mammal belonging to the taxonomic family Equidae. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into the large, single-toed animal of today.</p>
      <button class="remove-button">[x]</button>
    </div>
    <div class="pane">
      <h3>Donkey</h3>
      <p>The donkey or ass (Equus africanus asinus) is a domesticated member of the horse family, Equidae. The wild ancestor of the donkey is the African wild ass, E. africanus. The donkey has been used as a working animal for at least 5000 years.</p>
      <button class="remove-button">[x]</button>
    </div>
    <div class="pane">
      <h3>Cat</h3>
      <p>The domestic cat (Latin: Felis catus) is a small, typically furry, carnivorous mammal. They are often called house cats when kept as indoor pets or simply cats when there is no need to distinguish them from other felids and felines. Cats are often valued by humans for companionship and for their ability to hunt vermin.
      </p>
      <button class="remove-button">[x]</button>
    </div>
  </div>

JS:

<script>
    container.onclick = function(event) {
      //如果目标元素不是按钮-直接返回,什么都不做
      if (event.target.className != 'remove-button') return;
      
      //找到离按钮最近的pane
      let pane = event.target.closest('.pane');
      pane.remove();
    };
  </script>

 

posted @ 2020-07-11 19:52  LangZ-  阅读(156)  评论(0编辑  收藏  举报