I've never created a jQuery plug-in before. 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:
我以前从未创建过jQuery插件。我现在正在尝试并保持简单 - 这是我的插件代码,它在我公司的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. I do not get an alert box when I refresh my page. What am I doing wrong?
我这样做了吗?包含我的插件代码的JavaScript文件将根据Firebug返回到浏览器。刷新页面时,我没有收到警告框。我究竟做错了什么?
EDIT
The console reports an error:
控制台报告错误:
TypeError: $.displayToastrNotifications is not a function
TypeError:$ .displayToastrNotifications不是函数
$.displayToastrNotifications();
But, it is a function, at least I think it is...
但是,它是一个功能,至少我认为它是......
2 个解决方案
#1
4
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。
#2
4
since it is a plugin it need to be invoked in a jQuery wrapper object like
因为它是一个插件,所以需要在jQuery包装器对象中调用它
$('body').displayToastrNotifications();
Demo: Fiddle
#1
4
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。
#2
4
since it is a plugin it need to be invoked in a jQuery wrapper object like
因为它是一个插件,所以需要在jQuery包装器对象中调用它
$('body').displayToastrNotifications();
Demo: Fiddle