简体   繁体   English

如何在jQuery插件回调中使用'this'?

[英]How to use 'this' in jQuery plugin callback?

At the moment I am creating a jQuery plugin. 目前我正在创建一个jQuery插件。

I am facing a problem when using a callback. 使用回调时我遇到了问题。

Plugin code 插件代码

$.fn.bondye = function (options) {
    var settings = $.extend({
        callback: function () {}
    }, options);

    return this.each(function () {
        $(this).addClass('test');
        settings.callback();
    });
};

How I want to execute the code 我想如何执行代码

$(".myDiv").bondye({
    callback: function () {
        $(this).removeClass("test");
    }
});

jsFiddle example: http://jsfiddle.net/HEJtm/1/ jsFiddle示例: http//jsfiddle.net/HEJtm/1/

But I aint able to do anything with the div within the callback. 但我不能在回调中对div做任何事情。

I used http://learn.jquery.com/plugins/advanced-plugin-concepts/ to learn developing jQuery plugins, but I cannot find anything about callbacks. 我使用http://learn.jquery.com/plugins/advanced-plugin-concepts/来学习开发jQuery插件,但我找不到任何关于回调的信息。

You need to set the context for your callback. 您需要为回调设置上下文。 You can use call : 你可以使用call

settings.callback.call(this);

Option 1: 选项1:

Pass this back when you invoke callback() : 通过this ,当你调用回callback()

(function ($) {
    $.fn.bondye = function (options) {
        var settings = $.extend({
            callback: function () {}
        }, options);

        return this.each(function () {
            $(this).addClass('test');

            // Pass "this" back here:
            settings.callback(this);
        });
    };

})(jQuery);

$(".myDiv").bondye({
    callback: function (obj) {
        $(obj).removeClass("test");
    }
});

Here's a working fiddle . 这是一个工作小提琴

Option 2: (preferred) 选项2 :(首选)

(function ($) {
    $.fn.bondye = function (options) {
        var settings = $.extend({
            callback: function () {}
        }, options);

        return this.each(function () {
            $(this).addClass('test');
            settings.callback.call(this);
            settings.callback();
        });
    };

})(jQuery);

$(".myDiv").bondye({
    callback: function () {
        $(this).removeClass("test");
    }
});

Here's a working fiddle . 这是一个工作小提琴

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

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