2012-03-21 103 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()

相關問題