簡體   English   中英

jQuery插件允許多個實例

[英]Jquery plugin allow multiple instances

我正在使用jQuery 樣板模板編寫插件。 它基本上只運行ajax調用並替換其上運行的元素的內容。 例:

我的插件名稱是'getContent'

$('.container').getContent({
    html : 'foo'
});

插件的非常簡化的版本,但是在模板的最底部,是這樣的:

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations

$.fn[pluginName] = function(options) {
    this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
    });

    // chain jQuery functions
    return this;
};

顯然,它會進行一些檢查以查看pluginName是否已綁定到元素。 在這種情況下,當您稍后嘗試在同一頁面實例中再次執行該插件時,該插件將不會運行。

解決我的問題的正確方法是僅刪除new Plugin部分周圍的if嗎?

為了能夠為多個實例運行該插件,您需要為每個實例創建一個新的閉包,請嘗試以下代碼:

function getContentFunc(elem,options){
    //things you want your plugin to do
};

$.fn[pluginName] = function(options) {
    if ($.data(this, "plugin_" + pluginName)) return;
    return $(this).each(function() {
        getContentFunc(this,options);
        $.data(this, "plugin_" + pluginName);
    });
};

看到一個非常簡單的插件, 這里使用相同的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM