Foreword:
Event
The object represents the state of the event, such as the element in which the event occurred, the state of the keyboard button, the position of the mouse, and the state of the mouse button.
After the event occurs, the collection of a series of information data related to the event is placed in this object. This object is the event object event
, which has many properties and methods.
such as:
- Who bound this event.
- If the mouse triggers an event, you will get mouse related information, such as the mouse position.
- If the keyboard triggers an event, you will get information about the keyboard, such as which key was pressed.
In which event object propertiese.target
, and itthis
's pointing to vary.
Case:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
}
span {
display: block;
width: 50px;
height: 50px;
background-color: yellow;
}
</style>
</head>
<body>
<div>div
<span>span</span>
</div>
<script>
var div = document.querySelector('div');
div.addEventListener('click', function(e) {
console.log(this); // 给div绑定了事件,那么this就指向div
console.log(e.target); // e.target指向点击的那个对象
})
</script>
</body>
</html>
Preview:
Achieve results:
Click on the div:
this
Return div
label, e.target
return div
label
Click on span:
this
Return div
label, e.target
return span
label
analysis:
- Because
div
the click event is bound, allthis
returned arediv
; - Click
div
toe.target
returndiv
; clickspan
toe.target
returnspan
.
to sum up:
this
What is returned is the object (element) that binds the event; what ise.target
returned is the object (element) that triggered the event.- Simply put::
this
which element is bound to this click event, which element is returned;: which element is
e.target
clicked, which element is returned.