触发事件时如何触发父元素?
How to trigger the parent element when firing an event?
我想在每次单击按钮时控制台记录按钮,但如果我单击按钮内的任何子元素,则会打印子元素,这不是我想要的。如何确保打印具有事件侦听器的元素?
const onCrossClick = (e) => {
console.log(e.target);
};
<button
className="delete-button"
onClick={onCrossClick}
>
<i className="fas fa-times-circle fa-2x"></i>
</button>
const onCrossClick = (e) => {
console.log(e.currentTarget);
};
<button
className="delete-button"
onClick={onCrossClick}>
<i className="fas fa-times-circle fa-2x"></i>
</button>
使用closest()
.
const onCrossClick = (e) => {
console.log(e.target.closest("button"));
};
我想在每次单击按钮时控制台记录按钮,但如果我单击按钮内的任何子元素,则会打印子元素,这不是我想要的。如何确保打印具有事件侦听器的元素?
const onCrossClick = (e) => {
console.log(e.target);
};
<button
className="delete-button"
onClick={onCrossClick}
>
<i className="fas fa-times-circle fa-2x"></i>
</button>
const onCrossClick = (e) => {
console.log(e.currentTarget);
};
<button
className="delete-button"
onClick={onCrossClick}>
<i className="fas fa-times-circle fa-2x"></i>
</button>
使用closest()
.
const onCrossClick = (e) => {
console.log(e.target.closest("button"));
};