2013-07-14 6 views
0

Я не понимаю, почему я получаю два разных результата ниже. Я использую самый обычный рисунок JQuery плагин для Provide Public Access to Default Plugin Settings,Предоставить доступ к настройкам плагина по умолчанию: jquery plugin не работает, если не переместить его в конец элемента?

$.fn[pluginName].defaults = { 
    property: "value", 
    ... 
} 

Но я не могу получить правильный результат. Тогда я получаю правильный результат, если я сделал default как часть method - почему?

HTML,

<div class="hello1"></div> 

JQuery,

(function ($) { 

    var pluginName = 'hilight'; 

    var methods = { 

     init: function(options){ 

      var $this = this; 

      // Extend our default options with those provided. 
      // Note that the first argument to extend is an empty 
      // object – this is to keep from overriding our "defaults" object. 
      var o = $.extend(true, {}, $this[pluginName].defaults, options); 
      console.log(o.setup.element1); 

      // Call the local method from the plugin itself to get the processed options. 
      var o = $this[pluginName]('defaults',options); 
      console.log(o.setup.element1); 

     }, 

     defaults: function(options) { 

      // Default options. 
      var defaults = { 
       setup: { 
        tester1: "hello1", 
        tester2: "hello2", 
        tester3: "hello3", 
        element1: $(".hello1"), 
        element2: $(".hello2"), 
        list: $('.list-item') 
       }, 
       foreground: "red", 
       background: "yellow"   
      } 

      // Always leave this line here. 
      var options = $.extend(true, {}, defaults, options); 

      // Return the processed options. 
      return options; 

     } 
    } 

    $.fn[pluginName] = function(method) { 

     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); // always change 'init' to something else if you different method name. 
     } else { 
      $.error('Method ' + method + ' does not exist on jQuery.plugin'); 
     } 

     return this; 

    }; 

    // Provide Public Access to Default Plugin Settings 
    // An improvement we can, and should, make to the code above is to expose the default plugin settings. 
    // This is important because it makes it very easy for plugin users to override/customize the plugin with minimal code. 
    // And this is where we begin to take advantage of the function object. 
    // @reference: http://learn.jquery.com/plugins/advanced-plugin-concepts/ 

    // Plugin defaults – added as a property on our plugin function. 
    // This needs only be called once and does not 
    // have to be called from within a "ready" block 
    // $.fn.hilight.defaults.foreground = "blue"; 
    $.fn[pluginName].defaults = { 
     setup: { 
      tester1: "hello1", 
      tester2: "hello2", 
      tester3: "hello3", 
      element1: $('.hello1'), 
      element2: $(".hello2"), 
      list: $('.list-item') 
     }, 
     foreground: "red", 
     background: "yellow" 
    } 

}(jQuery)); 

дом готов,

$().hilight({setup:{tester1: "x"}}); 

результат,

Object[] // for --> var o = $.extend(true, {}, $this[pluginName].defaults, options); 
Object[div.hello1] // --> var o = $this[pluginName]('defaults',options); 

оба должны быть Object[div.hello1]

Любые идеи?

EDIT:

Он работает только если я перееду плагин в конце страницы или после элемента - как прийти ?? Как я могу заставить его работать, если я хочу разместить плагин в заголовке страницы?

ответ

1

Это потому, что DOM не готов.

Попробуйте обертывание ваш плагин вызова с:

$(document).ready(function() { 
    $().hilight({setup:{tester1: "x"}}); 
}); 
+0

спасибо за ответ. Я завернул его с '$ (document) .ready (function()' и 'window onload', но не повезло вообще! – laukok