js:Event.currentTarget與Event.target的區別

e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.javascript

舉個例子:css

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    #container {
        height: 200px;
        width: 100px;
        background-color: #333;
    }

    </style>
</head>
<body>

<div id="container">
    
    <button id="btn">button</button>

</div>

<script type="text/javascript">
function handle(e){
    console.log('e.currentTarget: ' + e.currentTarget.tagName);
    console.log('e.target: ' + e.target.tagName);
    console.log('this:' + this.tagName);
}

var div = document.getElementById('container');
div.addEventListener('click', handle, false);

</script>

</body>
</html>

事件是綁定到div上的,點擊div中的按鈕時:html

輸入圖片說明

點擊div中按鈕以外的區域時:java

輸入圖片說明

因爲是在div上綁定的點擊事件,因此handle中的this和e.currentTarget都指向div,而target指向鼠標點擊的那個元素。this

相關文章
相關標籤/搜索