我已经构建了一个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>
答案 0 :(得分:1)
尝试
$("#tip-test").get(0).ToolTip.showTip();
访问底层DOM元素!!