如何在单个页面上拥有多个jQuery插件实例? [英] How to have multiple instances of jQuery plugin on single page?

查看:104
本文介绍了如何在单个页面上拥有多个jQuery插件实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的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

希望有所帮助

Logan

这篇关于如何在单个页面上拥有多个jQuery插件实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆