2013-05-27 72 views
1

我已經構建了一個jQuery插件,我很努力地理解爲什麼我可以在一種情況下調用「public」方法,而不是其他方法。爲了便於閱讀,我試圖將插件剝離爲裸露的骨骼。當從.each()循環或從.click()函數返回對象時,爲什麼我可以調用它們的方法,但是直接找到對象並調用方法時,我不能調用它們的方法?見下文。無法訪問javascript對象的公共方法

甲小提琴是在http://jsfiddle.net/SSuya/

<script> 

// ==================================== 
// My Reusable Object: 
// ==================================== 

;(function ($, window, document, undefined) { 

    var pluginName = "ToolTip", 
     defaults = { 
      foo: 'bar', 
     }; 

    function Plugin(element, options) { 

     var widget = this; 

     this.element = element; 
     this.options = $.extend({}, defaults, options); 
     this._defaults = defaults; 
     this._name = pluginName; 
     this.element.ToolTip = this; 
     this.init(); 
    } 

    Plugin.prototype = { 
     init: function() { 
       alert("I'm ready!"); 
     }, 

     hideTip: function() { 
      alert("I'm hiding!"); 
     }, 

     showTip: function() { 
      alert("I'm showing!"); 
     } 

    }; 

    // A really lightweight plugin wrapper around the constructor, 
    // preventing against multiple instantiations 
    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
      } 
     }); 
    }; 

})(jQuery, window, document); 
</script> 



<html> 
    <body> 
    <div id='tip-test'>Target me!</div> 
    <input id='bad-button' type="button" onclick="badCode()" value="This won't work..."> 
    <input id='good-button' type="button" onclick="goodCode()" value="But this will...?"> 
    </body> 
</html> 

<script> 
    $("#tip-test").ToolTip(); // Works fine. 

    $("#bad-button").click(function(){ 
     $("#tip-test").ToolTip.showTip(); // This will generate an error 
    }); 


    $("#good-button").click(function(){ 
     $("#tip-test").each(function(){ 
       this.ToolTip.showTip(); // Will work just fine... 
      }); 
    }); 

</script> 

回答

1

嘗試

$("#tip-test").get(0).ToolTip.showTip();訪問底層DOM元素!!

+0

加 - 你說得對!我想現在我明白了 - 當我調用$(「#tip-test」)時,我沒有加載一個特定對象,我正在加載所有具有「tip-test」標識的對象。儘管它只會返回一個,但我仍然需要像數組一樣對待它。現在我明白了 - 謝謝凱文! – Anthony

+0

我建議調用'.get(0)',因爲這實際上會讓你訪問底層DOM元素,而不是JQuery包裝的元素。 –

+0

是的,有道理。謝謝凱文! – Anthony