javascript - 使用 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?
还有一种更简单的方法来编写点击事件监听器吗?
解决方案
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>
推荐阅读
- php - 自动生成html页面
- php - 调试 SQL 中的错误 1064 以查看长 SQL 语句的失败原因
- multithreading - 时间片的价格是多少?
- javascript - 如何让弹出表单在 jQuery 中工作?
- c# - HttpContext.Session.SetString() 在 .net core 3.1 中不起作用
- java - 不和谐 Java JDA | 哪个反应是addet
- json - 结构标签选项不为字段提供标签名称
- python - Matplotlib x 轴日期到日期时间格式
- javascript - 使用选定的 HTML 选项重新呈现表单
- regex - 冗余事务 id,同时匹配 perl 中的各种模式