编写适当的jQuery插件的麻烦

Zac*_*ura 0 javascript jquery

我正在重写一个jQuery插件,用于我在实习过程中构建的RSS阅读器.此插件使用Google的Feed API提取JSON格式的RSS Feed并将其返回给开发人员,从而允许他们微调控制该Feed在网页上的显示方式.我一直在关注官方jQuery插件创作页面作为参考.

在参考页面上,代码示例说你需要将你的插件添加到jQuery的原型:$.fn.这就是我所做的:

(function($) {
    "use strict";

    $.fn.rssObj = function(newUrl) {
        var RSSFeed = function(newUrl) {
            /*
             * An object to encapsulate a Google Feed API request.
             */

            this.feedUrl = newUrl;
        };

        RSSFeed.prototype.load = function() {
            var feed = new google.feeds.Feed(this.feedUrl);
            feed.load(function(result) {
                console.log(result);
            });
        };

        return new RSSFeed(newUrl);
    };

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

当我尝试通过执行使用此插件时$.rssObj("http://rss.test.com"),我的浏览器给了我这个错误:

$.rssObj() is not a function
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

T.J*_*der 5

要添加到$.fn,如果你想你的函数可用jQuery的情况下(例如,对象你回来$("your selector here")和这样).如果您希望$直接从对象获得您的功能,可以直接将其添加到对象中.

这是一个显示每个的例子:

// Creating the plugin
(function($) {
  
  // This will be on *instances*
  $.fn.green = function() {
    // `this` is the jQuery instance we were called on
    return this.css("color", "green");
  };
  
  // This will be on the $/jQuery object itself
  $.blue = function(selector) {
    // You don't use `this` here (you could if you want,
    // it will be === $/jQuery, but there's no reason to)
    $(selector).css("color", "blue");
    return this;
  };
  
})(jQuery);

// Usage
jQuery(function($) {
  
  // Make all divs green with a border
  $("div").green().css("border", "1px solid green");
  
  // Make all paragraphs blue
  $.blue("p");
  
});
Run Code Online (Sandbox Code Playgroud)
<div>I'm a div</div>
<p>I'm a paragraph</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)