The difference between JavaScript event object attribute e.target and this

Foreword:

EventThe 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:

  1. Who bound this event.
  2. If the mouse triggers an event, you will get mouse related information, such as the mouse position.
  3. If the keyboard triggers an event, you will get information about the keyboard, such as which key was pressed.
    In which event object properties e.target, and it this'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:
Insert picture description here

Achieve results:

Click on the div:
Insert picture description here

thisReturn divlabel, e.targetreturn divlabel


Click on span:
Insert picture description here

thisReturn divlabel, e.targetreturn spanlabel

analysis:

  1. Because divthe click event is bound, all thisreturned are div;
  2. Click divto e.targetreturn div; click spanto e.targetreturn span.

to sum up:

  1. thisWhat is returned is the object (element) that binds the event; what is e.targetreturned is the object (element) that triggered the event.
  2. Simply put::
    thiswhich element is bound to this click event, which element is returned;: which element is
    e.targetclicked, which element is returned.

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109270130