简体   繁体   中英

setTimeout() doesn't work with jQuery(this)

I've got this piece of script here, where I'd like to slide up my ul element, then after the slide up executed, I'd like to remove the "open" class for CSS reasons. What am I doing wrong?

 jQuery(this).parent().children("ul").slideUp(500); setTimeout(function(){ var elementToRemove = jQuery(this).parent(); elementToRemove.removeClass("open"); }, 500); 

this inside you callback function refers to the global object and not the event target.

Two solutions:

Use arrow functions (which preserve the this context):

jQuery(this).parent().children("ul").slideUp(500);
setTimeout(() => {
  var elementToRemove = jQuery(this).parent();
  elementToRemove.removeClass("open");
}, 500);

Or save a link to the this object:

jQuery(this).parent().children("ul").slideUp(500);
let that = this;
setTimeout(function(){
  var elementToRemove = jQuery(that).parent();
  elementToRemove.removeClass("open");
}, 500);

Solution 1

Use bind to pass the context to the function

jQuery(this).parent().children("ul").slideUp(500);

var func = function(){
  var elementToRemove = jQuery(this).parent();
  elementToRemove.removeClass("open");
}
setTimeout(func.bind(this),500);

Solution 2

jQuery(this).parent().children("ul").slideUp(500);
var self = this;
setTimeout(function(){
  var elementToRemove = jQuery(self).parent();
  elementToRemove.removeClass("open");
}, 500);

jQuery animations allow for an additional optional pararameter (a callback) called complete in the docs that will be executed once the animation is done. You can use it like this:

jQuery(this).parent()
            .children("ul")
            .slideUp(500, function(){
                var elementToRemove = jQuery(this).parent();
                elementToRemove.removeClass("open");
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM