如何在单个页面上有多个 jQuery 插件实例?

2022-01-11 00:00:00 jquery jquery-plugins javascript plugins

我正在编写一个简单的 jQuery 插件,但是我无法在一个页面上使用多个实例.

I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.

例如,这里有一个示例插件来说明我的观点:

For instance, here is a sample plugin to illustrate my point:

(function($) {
  $.fn.samplePlugin = function(options) {
    if (typeof foo != 'undefined')
    {
      alert('Already defined!');
    } else {
      var foo = 'bar';
    }
  };
})(jQuery);

然后如果我这样做:

$(document).ready(function(){
  $('#myDiv').samplePlugin({}); // does nothing
  $('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});

这显然是一个过于简单化的例子.所以我的问题是,我如何拥有插件的两个单独实例?我希望能够在同一页面上的多个实例中使用它.

This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.

我猜测问题的一部分可能在于在全局范围内定义变量.那我该如何定义它们对于该插件实例是唯一的呢?

I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?

感谢您的指导!

推荐答案

我有同样的问题,但我找到了一个非常方便的解决方案,我会发布给可能有这个问题的人

I have the very same problem but i find a very handy solution i´ll post it for someone who may have this problem

当您在插件中定义变量时,您可以使用 .data() 来存储您定义的所有变量

when you define your variables insinde the plugin you could use the .data() to store all the variables you define

喜欢这个

(function($) {
  $.fn.samplePlugin = function(options) {
    var base = this;
    this.foo // define foo

    // do stuff with foo and other variables

    // Add a reverse reference to the DOM object
    this.data("pluginname", base);

  };})(jQuery);

当你想使用相同的 foo 变量时,你应该用这个来检索引用:

And when you want to use the same foo variable you should retrive the reference with this:

base = this.data("pluginname");
base.foo

希望对你有帮助

洛根

相关文章