javascript - jQuery 插件无法正常工作

标签 javascript jquery css jquery-plugins

我正在开发一个名为“popup”的插件 ($(".messageBox").popup())。

这是我的部分代码:

$(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);

那是popup.min.js中的代码,下面是index.html中的代码:

$(function(){
    $(".messageBox").popup();
});

我的弹出窗口出现并正确淡入,但在 1000ms 后它没有淡出,因为它应该……我该怎么办?我打开了控制台,但没有显示任何错误。

最佳答案

因为setTimeout回调方法中的this引用是错误的

您可以使用闭包变量来保存引用

$(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);

或使用 $.proxy()将自定义上下文传递给回调

$(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);

关于javascript - jQuery 插件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17881047/

相关文章:

javascript - 将表单元素复制/粘贴到新行

javascript - Ajax 控制工具包 slider 处理程序图像定位

html - CSS Bootstrap : list-group-item hover+selected

javascript - 固定最大高度的文本换行

javascript - 使用 setter 和 getter

javascript - Google API V3 和说明 (Javascript)

javascript - 带拖放功能的 JQuery 可排序/可选择插件?

javascript - 如何包含 jquery.validate.js 文件(在本地目录中)并在表单验证中使用它?

带有 $(window).width() 的 jquery 条件需要重新加载

javascript - Meteor 中的 Template.created 和 Template.onCreated 有什么区别?