简体   繁体   English

setTimeout()不适用于jQuery(this)

[英]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. 我在这里有一段脚本,我想在其中向上滑动ul元素,然后在执行向上滑动之后,出于CSS原因,我想删除“ open”类。 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. 回调函数内部的this引用是指全局对象,而不是事件目标。

Two solutions: 两种解决方案:

Use arrow functions (which preserve the this context): 使用箭头函数(保留this上下文):

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: 或保存指向this对象的链接:

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

Solution 1 解决方案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 解决方案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. jQuery动画允许在文档中添加一个称为complete的附加可选参数(回调),动画完成后将执行该参数。 You can use it like this: 您可以像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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