简体   繁体   English

jQuery在设置插件选项之前添加变量

[英]jQuery add variable before setting plugin options

What is the best way to add a variable to this structure before setting plugin options? 在设置插件选项之前,向此结构添加变量的最佳方法是什么?

$('.example').somePlugin({
     option1: 1, 
     option2: 2
});

More details: Where can I add var selector = $(this) to use in the callback? 更多详细信息:在哪里可以添加var selector = $(this)以在回调中使用? I have to use the $('.example') selector in the callback. 我必须在回调中使用$('.example')选择器。

$('.example').somePlugin({
    option1: 1, 
    option2: 2,
    callback: function () {
      // use variable selector
    }
 });

One option is to loop through items and initialise the plugin on each instance, as follows: 一种选择是遍历项目并在每个实例上初始化插件,如下所示:

$('.example').each(function(){
    var $self = $(this);
    $self.somePlugin({
        option1: 1, 
        option2: 2,
        callback: function () {
          // I can use $self/$(this) for this callback now 

        }
    });
});

That way $(this) is a reference to a unique instance and is available to you for the callback 这样, $(this)是对唯一实例的引用,并且可用于回调

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

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