How to use "this" in this jquery function

I am trying to write a function where I need to reference "this" inside window.setTimeout. This is currently not working. How can I rewrite this so that it works? Thank.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          window.setTimeout("$(this).css('font-size','40px');",1000);
     });
 });
+3
source share
3 answers

As you saw, it thishas a different meaning inside setTimeout().

One solution is to store the correct value thisin the variable and reference it in the anonymous function that you pass.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          var th = this;
          window.setTimeout(function() {
                     $(th).css('font-size','40px');
                },1000);
     });
 });

Another option is to use jQuery $.proxy(), which will keep the value for you this.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          window.setTimeout($.proxy(function() {
                     $(this).css('font-size','40px');
                }, this)
          ,1000);
     });
 });

Otherwise, you can create a closure.

 $(function() {
     $('li a').click(function() {
          (function( th ) {
              $(th).parent().css('background-position','left top');
              window.setTimeout(function() {
                         $(th).css('font-size','40px');
                    }
              ,1000);
          })( this );
     });
 });
+4
source

setTimeout.

 $(function() {
      $('li a').click(function() {
            var $this = $(this);
            $this.parent().css('background-position','left top');
            window.setTimeout(function () {
                $this.css('font-size','40px');
            },1000);
          });
     });

.

0
     window.setTimeout(function(){$(this).css('font-size','40px')},1000);

. .

0

Source: https://habr.com/ru/post/1760185/


All Articles