I am working on a plugin called "popup" ( $(".messageBox").popup()
).
Here is part of my code:
$(this).fadeIn(settings.fadeDuration);
console.log($(this).attr("class"));
console.log(settings.timeOut);
setTimeout( function(){
console.log($(this).attr("class"));
$(this).fadeOut(settings.fadeDuration);
}, settings.timeOut);
that was the code in popup.min.js
, now below is the code in index.html
:
$(function(){
$(".messageBox").popup();
});
my popup appears, and fades in correctly, but it doesn't fade out after 1000ms
as it should... what can I do? I opened the console but there is no error shown.
because the this
reference is wrong inside the setTimeout
callback method
You can either use a closure variable to hold the reference
$(this).fadeIn(settings.fadeDuration);
console.log($(this).attr("class"));
console.log(settings.timeOut);
var el = this;
setTimeout( function(){
console.log($(el).attr("class"));
$(el).fadeOut(settings.fadeDuration);
}, settings.timeOut);
or use $.proxy() to pass a custom context to the callback
$(this).fadeIn(settings.fadeDuration);
console.log($(this).attr("class"));
console.log(settings.timeOut);
setTimeout($.proxy(function(){
console.log($(this).attr("class"));
$(this).fadeOut(settings.fadeDuration);
}, this), settings.timeOut);
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.