JQuery get source element in callback

$('.myElem').live('click', function() { $(this).hide(500, function() { $(this).siblings('.myOtherElem').show(); }); }); 

The above does not work because $(this) no longer in the correct scope in the callback. How to pass the original source element to a callback?

+4
source share
3 answers

Actually your code should work.

To access this inside the javascript internal method, you can save the link in the external area of ​​the method:

 $('.myElem').on('click', function() { var myElem = this; $(this).hide(500, function() { $(myElem).siblings('.myOtherElem').show(); }); }); 

However, in most jQuery methods this refers to the selector or element used:

 $('.myElem').on('click', function() { // This refers to the clicked element $(this).hide(500, function() { // This refers to the clicked element as well $(this).siblings('.myOtherElem').show(); }); }); 
+7
source
 $('.myElem').live('click', function() { var $this = $(this); $this.hide(500, function() { $this.siblings('.myOtherElem').show(); }); }); 
+2
source
 $('.myElem').live('click', function() { $(this).hide(500); $(this).siblings('.myOtherElem').show(); }); 
0
source

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


All Articles