改变事件目标

kar*_*una 2 html javascript javascript-events

我有以下html:

<div id="div1">
    <div id="div2">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

document.addEventListener('mousedown', function(e){
    console.log(e.target);
});
Run Code Online (Sandbox Code Playgroud)

如果鼠标在 div2 上点击,那么 e.target 就是 div2。在这种情况下,我希望目标是 div1。是否可以?

Ale*_*yne 5

最简单的方法可能是向上走 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);
});?
Run Code Online (Sandbox Code Playgroud)

示例:http : //jsfiddle.net/7kYJn/