onmouseover
就会触发。有没有一种很好的方法只在父节点上设置onmouseover
事件,但是它会在参数中传递当前悬停的元素(触发事件)?
<div id="parent" onmouseover="foo(triggerElement)"> <!-- this ofc doesn't work. How to write this? -->
<div id="child1" onmouseover="foo(this)">Child 1</div>
<div id="child2" onmouseover="foo(this)">Child 2</div>
<div id="child3" onmouseover="foo(this)">Child 3</div>
<!-- I don't want to set the same onmouseover event for each child -->
</div>
我当然可以使用javascript将参数'this'添加到div的每个孩子的onmouseover属性,但这似乎不太好。有更好的方式吗?
答案 0 :(得分:1)
这样的事情应该这样做
document.getElementById('parent').addEventListener('mouseenter', function(event) {
if (event.target !== this)
event.target.innerHTML = "You just hovered " + event.target.id;
}, true);