問題描述
我正在編寫一個簡單的 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
希望對你有幫助
洛根
這篇關于如何在單個頁面上有多個 jQuery 插件實例?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!