Home  >  Article  >  Web Front-end  >  The difference between target and this of event objects in Javascript

The difference between target and this of event objects in Javascript

autoload
autoloadOriginal
2021-04-09 10:25:511805browse

When learning event objects, I always think that target and this are the same. It was not until later that I discovered that the difference between the two is quite big. Today I will take you through Get up and take a look.

1. When the trigger object is consistent with the binding object

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul class="list">
        <li class="itm">item1</li>
        <li class="itm">item2</li>
        <li class="itm">item3</li>
        <li class="itm">item4</li>
        <li class="itm">item5</li>
    </ul>
    <script>
        const li=document.querySelector("ul li:nth-of-type(4)");
        console.log(li);

        li.addEventListener("click",function(e){
            console.log(e.target);
            console.log(this);
        });
    </script>
</body>

</html>

Click on item4this## After #li, both return as follows:

The difference between target and this of event objects in Javascript

2. When the trigger object is inconsistent with the binding object

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul class="list">
        <li class="itm">item1</li>
        <li class="itm">item2</li>
        <li class="itm">item3</li>
        <li class="itm">item4</li>
        <li class="itm">item5</li>
    </ul>
    <script>
        const ul=document.querySelector("ul");
        console.log(ul);
        ul.addEventListener("click",function(e){
            console.log(e.target);
            console.log(this);
        });
    </script>
</body>

</html>

After clicking

item4 thisli, the output is as follows:

The difference between target and this of event objects in Javascript

3. Summary:

  • target returns the event trigger object

  • this returns the event binding object

Recommended: "

2021 js interview questions and answers (large summary)

The above is the detailed content of The difference between target and this of event objects in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn