Home > Web Front-end > JS Tutorial > How to change this pointer in jquery

How to change this pointer in jquery

coldplay.xixi
Release: 2020-11-30 17:06:42
Original
3219 people have browsed it

How to change the point of this in jquery: 1. Use assignment [var that=this;] to change the point of [this] of the nested function; 2. Use the es6 arrow function to change the point of this, the code is [$( 'div').on('click', function()】.

How to change this pointer in jquery

The operating environment of this tutorial: windows10 system, jquery2.2.4, this article applies to all Brand of computer.

The method for jquery to change this pointed to:

Use assignment var that=this; to change the 'this of the nested function ' Point to

Use es6 arrow function to change this point to

    <script>
      function show() {
       alert(this)
      }
    //   show() //-> window
      //   show.call(document) // ->document  | 原生的方法
     $.proxy(show, document)() // ->document  | jQuery方法
  </script>
Copy after login

tips: For a function that passes parameters such as show (c1, c2) in the above example, use .proxy()There are also several scenarios where parameters are passed according to requirements, such as:            

1. .proxy(show, document, c1, c2) // -- > After adding (), call

2. .proxy( show, document )( c1, c2 ) // --> This is the direct call

    <script>
     // 利用赋值 var that = this; 来改变嵌套函数的&#39;this&#39;指向
       $(&#39;div&#39;).on(&#39;click&#39;, function() {
        var that = this
        setTimeout(function() {
           console.log(that) // -> div
       })
     })
   </script>
Copy after login
rrree

Related free learning recommendations: JavaScript (video)

The above is the detailed content of How to change this pointer in jquery. 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
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template