0
我創建了我的第一個jQuery插件,並希望創建jQuery對象,而是希望能夠控制剛創建的對象......jQuery插件,返回
我建立一個新的對象我的插件以下格式在這裏推薦:http://docs.jquery.com/Plugins/Authoring
這裏是我的測試代碼:
(function($){
var $this = $(this);
var methods = {
init : function(options) {
// methods.createDiv();
$this = $('<div>TEST CONTENT</div>')
.attr({ 'id':'test' })
.css({'color':'white','backgroundColor': 'red'})
.appendTo("body");
setTimeout(function(){
methods.green();
},
3000
);
return $this;
},
green : function() {
$this.css({'backgroundColor': 'green'});
},
blue : function() {
$this.css({'backgroundColor': 'blue'});
}
};
$.fn.myPlugin = 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);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tooltip');
}
};
})(jQuery);
$(document).ready(function() {
var myTest = $.fn.myPlugin();
myTest.blue();
});
最後,我希望能夠控制使用MYTEST變量新創建的div,但它不工作。我確信有很多明顯的作品我錯過了,而且我正在犯的錯誤,但這就是我在這裏發佈的原因。這是我的第一個插件,所以如果有人能夠幫助我獲得這個測試代碼並運行,我會很感激。目前,螢火報告: 「類型錯誤:myTest.blue是不是一個函數」
研究一些插件開發模式:http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns – 2013-03-05 00:01:20