我有以下html:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
如果在 div2 上单击鼠标,则 e.target 为 div2。在这种情况下,我希望目标是 div1。是否可以?
我有以下html:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
如果在 div2 上单击鼠标,则 e.target 为 div2。在这种情况下,我希望目标是 div1。是否可以?
最简单的方法可能是沿着 DOM 树向上走,直到找到所需的元素。
document.addEventListener('mousedown', function(e) {
// start with the element that was clicked.
var parent = e.target;
// loop while a parent exists, and it's not yet what we are looking for.
while (parent && parent.id !== 'div1') {
// We didn't find anything yet, so snag the next parent.
parent = parent.parentElement;
}
// When the loop exits, we either found the element we want,
// or we ran out of parents.
console.log(parent);
});
示例:http: //jsfiddle.net/7kYJn/
在 DOM 中,您可以指定将事件侦听器附加到哪个元素:
var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
console.log(e.target);
});