2013-05-27 70 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