1. 程式人生 > 實用技巧 >一個事件委託的例子

一個事件委託的例子

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>