首页 > 解决方案 > 使用 OOP 进行事件冒泡

问题描述

我正在尝试使用冒泡事件获取单击元素的 ID。

  const _elem = new WeakMap();

  class GetItem {
    constructor(e) {
      _elem.set(this, e);
    }

    eventBubblingTest() {
      const targetElement = _elem.get(this).target;
      return targetElement.parentNode.id;
    }
  }

  document.getElementById('parent').addEventListener('click', () => {
    const clickedID = new GetItem(event);
    alert(clickedID);
  });

目前我正在[object Object]作为输出。我的问题是为什么我没有得到点击子元素的 ID?

还有一种更简单的方法来编写点击事件监听器吗?

jsFiddle

标签: javascript

解决方案


Well, in your current code you are alerting the whole class (You just create a new instance of the GetItem and then trying to alert it). Instead of this, if you want to get the parentNode, id property you need to invoke the responsible function for it. So your code should be like this:

document.getElementById('parent').addEventListener('click', () => {
  const clickedID = new GetItem(event);
  alert(clickedID.eventBubblingTest());
});

Working Demo:

const _elem = new WeakMap();
const parent = document.getElementById('parent');

class GetItem {
  constructor(e) {
    _elem.set(this, e);
  }

  eventBubblingTest() {
    const targetElement = _elem.get(this).target;
    return targetElement.parentNode.id;
  }
}

parent.addEventListener('click', () => {
  const clickedID = new GetItem(event);
  console.log(clickedID.eventBubblingTest());
});
#parent {
  border: 1px solid #f00;
  display: flex;
  justify-content: space-evenly;
}

.product {
  min-width: 20%;
  background: #ccc;
  display: flex;
  flex-flow: column wrap;
  align-items: center;
  margin: 5px;
  padding: 8px;
}

img {
  max-width: 75%;
  height: auto;
}
<div id="parent">

  <div class="product" id="col1">
    <img src="https://cdn.freebiesupply.com/logos/large/2x/7up-13-logo-png-transparent.png" />
    <p> Items 1 </p>
    <button id="buyItem1"> Buy </button>
  </div>

  <div class="product" id="col2">
    <img src="https://cdn.freebiesupply.com/logos/large/2x/7up-13-logo-png-transparent.png" />
    <p> Items 2 </p>
    <button id="buyItem2"> Buy </button>
  </div>

  <div class="product" id="col3">
    <img src="https://cdn.freebiesupply.com/logos/large/2x/7up-13-logo-png-transparent.png" />
    <p id="sas"> Items 3 </p>
    <button id="buyItem3"> Buy </button>
  </div>

</div>


推荐阅读