简体   繁体   English

创建一个非常简单的jQuery插件,无法正常工作

[英]Creating a very simple jQuery plugin, not working

I've never created a jQuery plug-in before. 我以前从未创建过jQuery插件。 I'm trying it out and keeping it simple for now- here's my plug-in code which is hosted on a CDN in my company: 我现在正在尝试并保持简单 - 这是我的插件代码,它在我公司的CDN上托管:

(function ($) {

    $.fn.displayToastrNotifications = function () {
        alert('test');
    };

})(jQuery);

I'm referencing this JavaScript file inside my page: 我在我的页面中引用了这个JavaScript文件:

<script src="http://server/sites/CDN/Scripts/toastr-notifications.js"></script>

Finally, in the same page, I have: 最后,在同一页面中,我有:

$(document).ready(function () {
     $.displayToastrNotifications();
});

Am I doing this right? 我这样做了吗? The JavaScript file containing my plug-in code is being brought back to the browser per Firebug. 包含我的插件代码的JavaScript文件将根据Firebug返回到浏览器。 I do not get an alert box when I refresh my page. 刷新页面时,我没有收到警告框。 What am I doing wrong? 我究竟做错了什么?

EDIT 编辑

The console reports an error: 控制台报告错误:

TypeError: $.displayToastrNotifications is not a function TypeError:$ .displayToastrNotifications不是函数

$.displayToastrNotifications(); $ .displayToastrNotifications();

But, it is a function, at least I think it is... 但是,这是一个功能,至少我认为它是......

No, that's not right. 不,那不对。 You're adding the function to $.fn , so that means it's something to be used as a method of jQuery objects: 您将函数添加到$.fn ,这意味着它可以用作jQuery对象的方法:

$(something).displayToastrNotifications();

If you want a "global" function like $.ajax , then you'd set it up as just a property of $ , not $.fn . 如果你想要一个像$.ajax这样的“全局”函数,那么你将它设置为$的属性,而不是$.fn

since it is a plugin it need to be invoked in a jQuery wrapper object like 因为它是一个插件,所以需要在jQuery包装器对象中调用它

$('body').displayToastrNotifications();

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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