新手jQuery插件问题
我刚刚接触jQuery插件,我想用一个基本的面向对象插件模板做一个“hello world”练习。但是我无法使下面setup()函数中的console.log语句显示在firebug控制台窗口中 我这样称呼这个插件:新手jQuery插件问题,jquery,jquery-plugins,Jquery,Jquery Plugins,我刚刚接触jQuery插件,我想用一个基本的面向对象插件模板做一个“hello world”练习。但是我无法使下面setup()函数中的console.log语句显示在firebug控制台窗口中 我这样称呼这个插件: <script type="text/javascript" src="myPlugin.js" > <script type="text/javascript"> $(document).ready() { $('ul').myPlugin(
<script type="text/javascript" src="myPlugin.js" >
<script type="text/javascript">
$(document).ready() {
$('ul').myPlugin();
});
</script>
正如我所说,setup()函数中的console.log语句不会显示。我不知道为什么。但是,例如,如果我将console.log语句紧跟在顶行之后,它确实可以工作:
;(function($) {
console.log('hello world');
有人能告诉我我做错了什么吗 您的呼叫不正确:
<script type="text/javascript" src="myPlugin.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('ul').myPlugin();
});
</script>
$(文档).ready(函数(){
$('ul').myPlugin();
});
安布罗西亚指出了您询问的问题,因为您的电话不正确。您的.ready()
不包含该函数
但是,您可能需要考虑稍微不同地设置插件。现在,没有人可以在全局范围内覆盖您的默认设置,而您对.extend的使用会模糊您正在尝试的操作。这是我建议您设置插件的方式,但当然,每个人的做法都不同:
;(function($) {
$.fn.myPlugin = function(options) {
return this.each(function() {
(new $.MyPlugin(this, options));
});
};
$.MyPlugin = function(element, options) {
this.options = $.extend({}, $.MyPlugin.defaults, options);
this.setup = function(){
console.log(this.helloText);
};
this.setup();
};
$.MyPlugin.defaults = {
helloText: "hello World"
};
})(jQuery);
除了更容易理解之外,现在有人可以使用以下命令覆盖您对插件的所有调用的选项:
$.MyPlugin.defaults.helloText = "Something Else";
$('ul').myplugin(); // Outputs 'Something Else' to the console
我已经为jQuery插件编写了一个名为的助手,但是还有很多其他优秀的资源
$.MyPlugin.defaults.helloText = "Something Else";
$('ul').myplugin(); // Outputs 'Something Else' to the console