我已经构建了一个 jQuery 插件,但我很难理解为什么我可以在一种情况下调用“公共”方法,而在另一种情况下不能。为了可读性,我试图将插件剥离到裸露的骨头上。为什么我可以在从 .each() 循环或从 .click() 函数中返回对象时调用它们,但当我直接找到对象并调用方法时却不能?见下文。
小提琴位于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>