(function ($) {
$.fn.userLogin = function (options) {
// 默认值
var defaults = {
url: '/UserLogin/Login', // URL
userName: $(this).find("input[name='userName']"), // 用户名控件
passWord: $(this).find("input[name='password']"), // 密码控件
identifyingCode: $(this).find("input[name='identifyingCode']"), // 验证码控件
rememberPwd: $(this).find("input[name='rememberpwd']"), // 是否记住密码控件
skipUrl: '/Home/Index', // 登录成功跳转页面url
msg: $(this).find('#msg'), // 返回消息控件id
btnSubmitId: '#BtnId' // 提交控件id
};
var obj = $.extend(defaults, options);
// 登录
function submit() {
var userNameInput = $.trim(obj.userName.val());
var passwordInput = $.trim(obj.passWord.val());
var identifyingCodeInput = false;
if (userNameInput == '') {
obj.userName.focus();
return;
}
if (passwordInput == '') {
obj.password.focus();
return;
}
$.ajax({
url: obj.url,
type: 'post',
dataType:'html',
async: true,
cache: false,
data: {
userName: obj.userName,
password: obj.passWord,
identifyingCode: obj.identifyingCode,
rememberPwd:obj.rememberPwd
},
success: function (data) {
if (data == 1) {
alert('登录成功');
location.href = obj.skipUrl;
}else if(data == 0){
alert('验证码错误!');
obj.identifyingCode.focus();
}else {
alert('登录失败');
obj.userName.focus();
}
}
});
}
// 返回消息
function showMsg(msg) {
obj.msg.html(msg);
}
// 绑定登录按钮事件
obj.btnSubmitId.bind('click', function () {
submit();
return false;
});
};
})(jQuery);
$.extend({
getJson: function (url, data, success) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json',
async: true,
cache: false,
data: data,
success: function (result) {
success(result);
}
});
},
postJson: function (url, data, success) {
return $.ajax({
url: url,
type: 'post',
dataType: 'json',
async: true,
cache: false,
data: data,
success: function (result) {
success(result);
}
});
}
});
页面调用
<script type="text/javascript">
$('#form1').userLogin({
url: '/UserLogin/Login', // URL
userName: $("input[name='userName']"), // 用户名控件id
passWord: $("input[name='password']"), // 密码控件id
identifyingCode: $("input[]"), // 验证码控件id
rememberPwd: '#rememberPwd', // 是否记住密码控件id
skipUrl: '/Home/Index', // 登录成功跳转页面
msg: '#msg', // 返回消息控件id
btnSubmitId: $("#btnSumit") // 提交控件id
}); </script>
使用命名空间
虽然在jQuery命名空间中,我们禁止使用了大量的javaScript函数名和变量名。但是仍然不可避免某些函数或变量名将于其他jQuery插件冲突,因此我们习惯将一些方法封装到另一个自定义的命名空间。
jQuery.myPlugin = {
foo:function() {
alert('This is a test. This is only a test.');
},
bar:function(param) {
alert('This function takes a parameter, which is "' + param + '".');
}
};
采用命名空间的函数仍然是全局函数,调用时采用的方法:
$.myPlugin.foo();
$.myPlugin.bar('baz');