簡體   English   中英

如何使jQuery插件函數可以獨立使用,不能在集合上運行

[英]How to make a jQuery plugin function callable for stand-alone use, that does not operate on a collection

我閱讀了插件創作jquery文檔,並熟悉它。 但是,給出的示例始終對一組先前匹配的元素進行操作。 我想創建一個可以同時執行這兩項操作的函數:

// example usage of my to-be-created plugin function

// this is the way described in the docs, and I know how to do that
$("a").myFunction ()

// but I also want to be able to call the function without a collection:
$.myFunction ();

如果在沒有要操作的集合的情況下調用$.myFunction () ,它將創建它自己的要匹配的元素集合 - 一種初始化過程(但不一定只運行一次)。 此外, $.myFunction ()應保持可鏈接性。

我想要實現的偽代碼:

// [...]
function myFunction (): {
    if (notCalledOnACollection) {
        // this should run when called via $.myFunction ()
        $elements = $("a.myClass");
    }
    else {
        $elements = $(this);
    }
    return $elements.each (function () {
        // do sth. here 
    });
}

我真的希望將所有函數實現/功能保留在單個函數定義中,並且在jQuery對象中的兩個單獨位置中沒有兩個單獨命名的函數或兩個同名函數。

當然我可以添加一個參數myFunction (do_init)來指示要執行的if語句的哪個分支,但這會使我的參數列表混亂(我想對多個插件使用該方法,並且會有myFunction ()參數為了簡單起見我剛剛離開這里。

有什么好建議嗎?

只需在插件定義中添加另一個引用,您就可以輕松使用標准插件代碼:

(function( $ ) {
    $.myPlugin = $.fn.myPlugin = function(myPluginArguments) {
        if(this.jquery)
            //"this" is a jquery collection, do jquery stuff with it
        } else {
            //"this" is not a jquery collection
        }
    };

    $.fn.myPlugin.otherFunc = function() {
    };
})( jQuery );

這里唯一的區別是$.myPlugin = part,它允許你直接調用你的插件而不運行jquery的選擇器函數。 如果您確定需要其他功能或屬性,可以將它們創建為插件的屬性。

用法:

//using a selector (arguments optional)
$(".someClass").myPlugin();

//using the options variable - or whatever your arguments are
$.myPlugin({id: "someId"});

//accessing your other functions/properties
$.myPlugin.otherFunc();

暫無
暫無

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

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