目前我有一個文件,我命名爲JQuery.ext.js,其中包括我的所有頁面。在這個文件中我有許多功能是不喜歡的東西下面,包含jQuery ext函數的最佳做法是什麼?
(function($) {
/**
* Checks to see if a container is empty. Returns true if it is empty
* @return bool
*/
$.fn.isEmptyContainer = function() {
//If there are no children inside the element then it is empty
return ($(this).children().length <= 0) ? $(this) : false;
};
/**
* Strip html tags from elements
* @return jQuery
*/
$.fn.stripHTML = function() {
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
//Loop through all elements that were passed in
this.each(function() {
$(this).html($(this).html().replace(regexp, ""));
});
return $(this);
};
/**
* This function will check the length of a textarea and not allow the user to go beyond this length.
* You should use the onkeypress event to trigger this function
*
* @param event event This value should always be event when passing it into this function
* @param maxlength int The maximum amount of character that the user is allowed to type in a textarea
*/
$.fn.enforceMaxLength = function(event, maxlength) {
//Only allow the client code to use the onkeypress event
if(event.type == 'keypress') {
//If the client code does not pass in a maxlength then set a default value of 255
var charMax = (!maxlength || typeof(maxlength) != "number") ? 255 : maxlength;
//If the user is using the backspace character then allow it always
if(event.which == 8) { return true; }
//Else enforce the length
else { return ($(this).val().length <= charMax); }
}
//Will only get here if the event type is not keypress
return false;
};
})(jQuery);
是否有另一種方式做到這一點?或者這是大多數人這樣做的方式?
感謝您的幫助,新都
EDITED
添加不同的插件的代碼並刪除了驗證插件
感謝您的幫助favio。實際上,這裏不僅僅是驗證功能。這些恰好是該文件中的前幾個。你說我實際上在這裏使用插件,是的,我已經將它們設置爲插件格式,但是你認爲我應該以不同的方式做到這一點嗎?我將在這裏添加一些其他函數,並刪除驗證函數以向您展示我需要組織的一些其他函數。 – Metropolis 2010-05-17 12:55:48
沒問題。 :)我已經更新了我的答案,希望有幫助! – Favio 2010-05-17 15:05:25
太棒了!非常感謝Favio的幫助。我相信你能幫助我理解,如果我至少在某種程度上是正確的。我會試着更多地思考這個問題,並找到一種在邏輯莊園中區分這些問題的方法。 – Metropolis 2010-05-17 16:09:11