我目前正在編寫我的第一個jQuery插件,我正在努力尋找一種合適的方式來構造代碼。我已經閱讀了jquery網站上的文檔以及其他插件的源代碼,但似乎無法找到達成一致的方式或解決我遇到的問題。jQuery插件範圍建議
該插件將一些文本處理添加到文本輸入元素以將文本格式化爲日期。
下面的示例將兩個事件綁定到元素。我遇到的問題是如何從_processText函數訪問元素本身。在這個例子中,我使用$(this),但是這給了我的對象,而不是元素,所以我不能設置它的值或觸發事件。我發現這樣做的唯一方法是直接在綁定事件中將元素作爲參數傳遞給函數,但我認爲這看起來不正確。
大大收到的任何幫助。
(function($) {
var methods = {
init : function(options) {
return this.each(function() {
// Process the entered text and convert
// into a formatted date
$(this).bind('blur', function(event){
methods._processText($(this).val());
});
// Custom event to trigger when invalid text
// is entered
$(this).bind('invalid', function(event) {
alert("Invalid");
});
});
},
_processText: function(txt) {
// Sudo code
if (txt.isValid()) {
$(this).val(txt)
} else {
$(this).trigger("invalid");
}
}
};
// boilerplate
$.fn.datefield = 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.DateField');
}
};
})(jQuery);
嘗試'this.',而不是'$(本).' – Sparky
@ Sparky672這不會工作,因爲這將是指你在功能 –