编写适当的jQuery插件的麻烦 [英] Troubles Writing A Proper jQuery Plugin

查看:62
本文介绍了编写适当的jQuery插件的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写一个jQuery插件,该插件将在实习期间构建的RSS阅读器中使用.此插件使用Google的Feed API提取JSON格式的RSS提要,并将其返回给开发人员,从而使他们可以对该提要在网页上的显示方式进行微调控制.我一直在遵循官方 jQuery插件创作页面作为参考.

I'm in the process of rewriting a jQuery plugin to be used in an RSS reader I'm building during an internship. This plugin uses Google's Feed API to pull a JSON-formatted RSS feed and return it to the developer, allowing them fine-tuned control over how that feed is displayed on the webpage. I have been following the official jQuery Plugin Authoring page as a reference.

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

On the reference page, code examples say that you need to add your plugin to jQuery's prototype: $.fn. Here's what I've done:

(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);

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

When I attempt to use this plugin by executing $.rssObj("http://rss.test.com"), my browser gives me this error:

$.rssObj() is not a function

我在做什么错了?

推荐答案

如果希望函数在jQuery 实例上可用,则添加到$.fn(例如,从中获取的对象) $("your selector here")等).如果希望直接从$对象获得功能,则可以直接将其添加到其中.

You add to $.fn if you want your function to be available on jQuery instances (e.g., the objects you get back from $("your selector here") and such). If you want your function available from the $ object directly, you add it directly to it.

以下是显示每个示例的示例:

Here's an example showing each:

// 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");
  
});

<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>

这篇关于编写适当的jQuery插件的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆