我有一个动态生成的列表,其中包含应在上执行操作的复杂组件mouseover
。
由于我使用Angular,因此我尝试在组件的最高父元素上使用(mouseover)="onhover($event)"
和进行构建(mouseout)="onhover($event)
,以获取它,然后从那里路由到应更改的不同组件。
<div class="my-list_element" id="{{'my-list_element' + i}}" (mouseover)="onhover($event)" (mouseout)="onhover($event)" >
然后,打字稿代码通常具有捕获事件的功能:
onhover(event: Event){
let id = (event.target as HTMLInputElement).id;
console.log(id.toString());
}
在测试它是否有效时,我注意到,如果我不直接将鼠标悬停在组件的父项上,则子项的ID会记录在控制台中,这不会使到应该更改的元素的静态路由成为可能。
是否可以在整个组件上保留mouseover
/ mouseout
,但仍仅获取整个组件的最高父级的ID?
您可以参考event.currentTarget
而不是event.target
:
事件接口的currentTarget只读属性始终指向事件处理程序已附加到的元素,而Event.target则相反,后者标识发生事件的元素,也可能是事件发生的原因。后裔。
在下面的代码段中,请注意,无论哪个元素触发了事件,currentTarget
始终都是包含<li>
元素:
function doStuff(e) {
console.clear();
console.log(`target: ${e.target.className}`); // div-child
console.log(`currentTarget: ${e.currentTarget.className}`); // li-parent
}
ul {
list-style: none;
margin: 0;
padding: 1rem;
background: tomato;
}
li {
padding: 0.25rem;
background: bisque;
}
li div {
background: white;
margin: 0.5rem;
padding: 0.5rem;
}
<ul>
<li class="li-parent" onmouseover="doStuff(event)">
<div class="div-child">child 1</div>
<div class="div-child">child 2</div>
</li>
</ul>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句