Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the difference between this and event in JS

黄舟
Release: 2017-10-24 09:33:05
Original
2222 people have browsed it

Today I saw the two parameter passing forms of this and event in the chapter "Introduction to JavaScript - Events". Because as a junior front-end developer, I have only used this to pass parameters, so I really want to figure out what is the difference between this and event, and which one is more appropriate to use under what circumstances.

onclick = changeImg(this) vs onclick = changeImg(event)


##

<img src=&#39;usa.gif&#39; onclick="changeImg(event)" />
<script>
  var myImages = [
    &#39;usa.gif&#39;,&#39;canada.gif&#39;,&#39;jamaica.gif&#39;,&#39;mexico.gif&#39;
  ];
  function changeImg(e) {
    var el = e.target;
    var newImgNumber = Math.round(Math.round()*3);
    while(el.src.indexOf(myImages[newImgNumber]) != -1){
      el.src =myImages[newImgNumber];
    }
  }
</script>
Copy after login

1.this is a keyword in Javascript language.

2.this represents an internal object automatically generated when the function is running and can only be used inside the function.

3. The difference between this and event.target:

Events in js will bubble up, so this can change, but event.target will not change (when the event is triggered , only passing the reference of the current event object), it is always the target DOM element that directly accepts the event;

In addition, this and event.target are both DOM objects. If you want to use the method in jquey, you can convert them For jquery objects: $(this) and $(event.target);

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!