找到你要的答案

Q:jQuery add variable before setting plugin options

Q:jQuery添加变量前设置插件选项

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? I have to use the $('.example') selector in the callback.

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

在设置插件选项之前,向这个结构添加变量的最好方法是什么?

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

更多细节:我在哪里可以添加var选择器= $(这)在回调中使用?我必须使用回调中的$(。

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

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

一种选择是通过循环项目和初始化插件的每个实例,如下:

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

        }
    });
});

这样($)是对一个唯一实例的引用,并为您提供回调

javascript  jquery  callback