简体   繁体   中英

How to write and/or call a jQuery plug-in?

I'm trying to follow this article to write a simple jQuery plugin: http://brolik.com/blog/how-to-create-a-jquery-plugin/

I seem to always get the following error in my console: 未捕获的TypeError:$(...)。blogPost不是函数

HTML

<div id="prod-part">TODO write content</div>   

Javascript

(function($){
    $.blogPost = function(el, options) {
        var base = this;

        base.$el = $(el);
        base.el = el;

        base.$el.data('blogPost', base);

        base.init = function(){
            console.log("hello");
        };
    };
})(jQuery);

$(function () {
    $('#prod-part').blogPost();

});

Here is a simple jsfiddle which still creates the issue. I'm not sure If I am calling on the plug-in incorrectly or if the plugin is coded incorrectly. I've tried jQuery versions 1.7.2 and 1.11.0 and still come out with the same results. Any suggestions would be greatly appreciated. http://jsfiddle.net/45oLp31m/1/

Background:

The jQuery function ( jQuery() or $() ) acts as a factory to return a new instance of jQuery collection when you pass in a selector. So $('#foo') returns an instance of jQuery collection. In order to call methods off of that instance, like $('#foo').somePlugin() , those methods have to be defined on the instance. The primary way we get methods onto instances is to add them to the constructor's prototype.

Solution

So the solution to your specific error is that jQuery plugins are defined on the jQuery collection constructor's prototype. This prototype is aliased at jQuery.fn (and jQuery is aliased as $ , so $.fn is also ok). Adding methods to the prototype is as simple as $.fn.somePlugin = function () {} .

Thus your plugin needs to be defined like:

$.fn.blogPost = function(el, options) {

More

As I said, this is for the specific error you quoted. I assume at this point that you haven't made it much further in your tutorial, so I won't go into the other issues in your code (like the fact that your plugin does not return the collection for chaining).

Instead of

$.blogPost = function(el, options) {...}

Try

$.fn.blogPost = function(el, options) {...}

Functions in the $.fn namespace are available as methods on jQuery collections, which is what you want.

$(selector).blogPost();

Such methods a generally known as "plugins".

In other (rarer) circumstances, you might want to extend the jQuery namespace itself, in which case your $.foo = function() {...} would be applicable. Such functions are known as "static methods".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM