改变事件目标

时间:2012-12-31 23:58:09

标签: javascript html javascript-events

我有以下html:

<div id="div1">
    <div id="div2">
    </div>
</div>

JS:

document.addEventListener('mousedown', function(e){
    console.log(e.target);
});

如果在div2上单击鼠标,则e.target为div2。在这种情况下,我希望目标是div1。有可能吗?

2 个答案:

答案 0 :(得分:4)

最简单的方法可能是向上走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/

答案 1 :(得分:1)

在DOM中,您可以指定将事件侦听器附加到的元素:

var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
   console.log(e.target);
});