【问题标题】:How to change scope of 'this' in settings for custom jQuery plugin如何在自定义 jQuery 插件的设置中更改“this”的范围
【发布时间】:2012-05-28 11:54:36
【问题描述】:

使用很多 jQuery 函数,我可以编写如下代码:

$('.element').css({
    'width':    $(this).width() * 2
});

通过使用 $(this) 我可以找到 .element 的宽度。

如何让我自己发明的插件以同样的方式工作?

$('.element').myPlugin({
    'setting':    $(this).width() * 2
});

仅出于演示目的,这可能是我的插件代码的样子:

$.fn.myPlugin = function(settings){

    // Settings
    var defaults = {
        'setting':    'value'
    };

    var o = $.extend(defaults, settings);

    // For every instance
    return this.each(function(){

        // Do something

    });

};

希望这是有道理的,如果有人可以为这个问题建议一个更好的标题,请随意!当您不知道要使用什么术语时,很难搜索!

【问题讨论】:

    标签: jquery jquery-plugins scope


    【解决方案1】:

    你能证明这一点吗:

    $('.element').css({
        'width':    $(this).width() * 2
    });
    

    按照你的描述工作???如果是这样,我会很困惑。

    【讨论】:

    • 在同样的上下文中,你可以用它来初始化你的插件吗?您会看到 jQuery 将 this 绑定到 click 处理程序中的目标。
    • 啊,好的,谢谢你的解释。我现在真的应该想通了!
    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多