一个事件委托的例子

时间:2020-07-11
本文章向大家介绍一个事件委托的例子,主要包括一个事件委托的例子使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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>

原文地址:https://www.cnblogs.com/LangZ-/p/13285214.html