1 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
好吧,在您當(dāng)前的代碼中,您正在提醒整個(gè)班級(您只需創(chuàng)建一個(gè)新實(shí)例GetItem,然后嘗試提醒它)。取而代之的是,如果您想獲得parentNode,id屬性,則需要為其調(diào)用負(fù)責(zé)的函數(shù)。所以你的代碼應(yīng)該是這樣的:
document.getElementById('parent').addEventListener('click', () => {
const clickedID = new GetItem(event);
alert(clickedID.eventBubblingTest());
});
工作演示:
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>
添加回答
舉報(bào)