2

私は次のhtmlを持っています:

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

JS:

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

div2 でマウスをクリックすると、e.target は div2 になります。この場合、ターゲットをdiv1にしたい。出来ますか?

4

2 に答える 2

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);
});​

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

于 2013-01-01T00:06:29.113 に答える
1

DOM では、イベント リスナーをアタッチする要素を指定できます。

var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
   console.log(e.target);
});
于 2013-01-01T00:11:38.353 に答える