我对我的一个项目的 javascript 混乱不满意,所以我决定把所有东西都放在下面的插件结构中。请注意,我是一名 C# 开发人员,不会对 jQuery 做太多事情,但它看起来很有趣。
(function($) {
var methods = {
init: function(options) {
if (!cookiesEnabled()) {
window.location = "http://www.mysite.com/error?msg=nocookies";
}
// autosize middle frame if right side has no content
autosizeframes('#right-side');
// EVENTS
$(document).on('submit', '#signin_form', function (event) {
event.preventDefault();
postAjaxForm($(this));
});
$(document).on('submit', '#register_form', function (event) {
event.preventDefault();
postAjaxForm($(this));
});
$(document).on('click', '.user-settings', function (e) {
var menu = $(this).parent().children('#menu');
if ($(menu).is(':visible')) {
$(menu).slideUp(500);
} else {
$(menu).slideDown(500);
}
});
}
};
// METHODS Commonly Used
var postAjaxForm = function(form) {
var updateElement = $(form).attr('UpdateElement');
if (!$(updateElement).length) {
alert('Unable to find update element');
return false;
}
if ($(form).valid()) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(response) {
$(updateElement).html(response);
$.validator.unobtrusive.parse($(updateElement).find('form'));
},
error: function(xhr,stats,errorMessage) {
}
});
}
return true;
};
var checkLength = function(element) {
if ($.trim(element).length) {
return true;
}
return false;
};
var autosizeframes = function(element) {
if (!$.trim($(element).len)) {
$('#middle').width($('#middle').width() + $(element).width());
}
};
var cookiesEnabled = function() {
var enabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.enabled == "undefined" && !enabled) {
document.cookie = "_test";
enabled = (document.cookie.indexOf("_test") != -1) ? true : false;
}
return enabled;
};
$.fn.site = 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');
}
};
})(jQuery);
输入赞赏和感谢