2009-11-17 67 views
1

我刚刚进入jQuery插件,我想用一个准系统面向对象的插件模板做一种'hello world'练习。但是我无法在下面的setup()函数中获取console.log语句以在Firebug控制台窗口中显示。新手jQuery插件问题

我所说的插件,像这样:

<script type="text/javascript" src="myPlugin.js" > 
<script type="text/javascript"> 
    $(document).ready() { 
    $('ul').myPlugin(); 
    }); 
</script> 

myPlugin.js:

;(function($) { 

    $.fn.extend({ 
     myPlugin: function(options) { 
      return this.each(function() { 
       new $.MyPlugin(this, options); 
      }); 
     } 
    }); 

    $.MyPlugin = function(element, options) { 
     var defaults = {   
      helloText: "hello World"   
     } 

     this.options = $.extend({}, defaults, options || {}); 

     this.setup();  
    }; 

    $.extend($.MyPlugin.prototype, { 

    setup: function() { 
     console.log(this.helloText);   
    } 
    }); 
})(jQuery); 

就像我说的,在设置()函数不显示的console.log语句。我不知道为什么。但是,如果我把一个的console.log语句紧随顶线,例如,它的工作:

;(function($) { 
    console.log('hello world'); 

.....有人可以告诉我,我做错了什么?

回答

2

您的来电是不正确的:

<script type="text/javascript" src="myPlugin.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
     $('ul').myPlugin(); 
    }); 
</script> 
0

豚草指出你问的问题,因为你的电话是不正确的。您的.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插件的辅助称为Starter for jQuery但也有吨的其他伟大的资源在那里。