2012-03-21 51 views
-1

我做错了什么?它在jquery文档中建议的分离方法之前就工作过了。 呼叫:$(this).Slick('show');这个简单的jquery插件示例有什么问题?

(function ($) { 

var methods = { 

    // object literals for methods 
    init: function (options) { 

     // initialize settings 
     var settings = $.extend({ 
      'location': 'center', 
      'speed': 'normal' 
     }, options); 
    }, 
    show: function() { 

     return this.each(function() { 

      // plugin code here 
      alert('success!'); 
     }); 
    }, 
    hide: function() { 

     // hide 
    } 
}; 

$.fn.Slick = function (method) { 
    // method calling logic -- jquery recommended/standard 
    if (methods[method]) { 
     return methods[method].apply(this, Array.prototype.slice.call(arguments 1)); 
    } else if (typeof(method === 'object' || !method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.Slick'); 
    } 
}; 
})(jQuery); 
+2

工作一切“它的工作之前,我分离方法” ---回滚代码到它的工作状态。再次重复同样的步骤,逐行进行。每次微小的迭代后,检查一切是否按预期工作。当你弄坏它时 - 你肯定知道究竟是什么原因引起的一小部分变化(它被称为**调试**) – zerkms 2012-03-21 22:08:33

回答

3

有两种语法错误。

缺少逗号:

return methods[method].apply(this, Array.prototype.slice.call(arguments 1)); 

缺少右括号:

} else if (typeof(method === 'object' || !method) { 
+1

应该这样做。你真的应该安装Firebug或使用其他浏览器的开发工具之一。 Firebug的控制台立即抛出一个错误指出语法错误。 – Jason 2012-03-21 22:10:20

1

其他财产以后可能对你有用。我很长时间很难编写jQuery插件,直到我最终创建了这个简单的公式,自从我开始使用它以来,它一直在为我工作。

(function($) { 
    if (!$.myExample) { 
     $.extend({ 
      myExample: function(elm, command, args) { 
       return elm.each(function(index){ 
        // do work to each element as its passed through 
       }); 
      } 
     }); 
     $.fn.extend({ 
      myExample: function(command) { 
       return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1)); 
      } 
     }); 
    } 
})(jQuery); 

这给了你,你需要开始建立一个jQuery插件,将在典型的jQuery的方式通过两个$.myExample($("someEle"))$("someEle").myExample()

相关问题