prototype
'abc'.repeatStringNumTimes(3) // abcabcabc
String.prototype.repeatStringNumTimes = String.prototype.repeatStringNumTimes || function(times) {
var str = '';
for(var i = 0; i < times; i++) {
str += this;
}
return str;
}
jQuery
$.extend({
sayHello: (name) {
console.log('Hello,' + (name ? name : 'Dude') + '!');
}
})
$.sayHello(); 调用
$.sayHello('Wayou'); 带参调用
定义Beautifier的构造函数
var Beautifier = (ele,opt) {
this.$element = ele,this.defaults = {
'color': 'red','fontSize': '12px'
},1)">this.options = $.extend({},.defaults,opt)
}
定义Beautifier的方法
Beautifier.prototype = {
beautify: () {
return .$element.css({
'color': .options.color,'fontSize': .options.fontSize,'textDecoration': .options.textDecoration
});
}
}
在插件中使用Beautifier对象
$.fn.myPlugin = (options) {
创建Beautifier的实体
var beautifier = new Beautifier(调用其方法
beautifier.beautify();
}
$(() {
$('a').myPlugin({
'color': '#2C9929'
});
})
vue
MyPlugin.install = (Vue,options) {
1. 添加全局方法或属性
Vue.myGlobalMethod = () {
逻辑...
}
2. 添加全局资源
Vue.directive('my-directive' }
...
})
3. 注入组件
Vue.mixin({
created: () {
4. 添加实例方法
Vue.prototype.$myMethod = (methodOptions) {
}
}
export default MyPlugin
调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
Vue.use(MyPlugin,{ someOption: true })
一般方案
<form action="" id="registerForm" method="post" onsubmit="return submitValidate()">
p>
label>请输入用户名:</input type="text" name="userName" />
>请输入密码:="password" >请输入手机号码:="phoneNumber" divbutton ="submit">提交buttonform>
submitValidate() {
var registerForm = document.getElementById("registerForm");
var rulesArr = [
{
el: registerForm.userName.value,rules: [{rule: 'isNonEmpty',message: '用户名不能为空'},{rule:'minLength:3',message: '用户名长度不能小于3位'}]
},{
el: registerForm.password.value,message: '密码不能为空'},{rule:'minLength:6',message: '密码的长度不能小于6位'}]
}
]
var resultMsg = validate.check(rulesArr);
if(resultMsg) {
alert(resultMsg);
falsetrue;
}
var validate = (() {
校验规则的各种算法
var rules = {
判断非空
isNonEmpty: (value,errorMsg) {
if(!value) {
errorMsg;
}
},1)"> 判断最小长度
minLength: if(value.toString().length < length) {
判断最大长度
maxLength: if(value.toString().length > 判断手机号
isMobile: if (!/(^1[0-9]{10}$)/.test(value)) {
判断座机电话
isTel: if(!/^\d{3}-d{8}|d{4}-d{7}|d{11}$/ errorMsg;
}
}
}
/** 校验方法
* @param {Array} arr
* @return {*}
* */
check: (arr) {
var ruleMsg;
checkRule;
_rule;
var i = 0,len = arr.length; i < len; i++) {
没有当前校验字段
if(arr[i].el === undefined) {
return '没有当前字段'
}
var j = 0,ruleLen = arr[i].rules.length; j < ruleLen; j++) {
var ruleObj = arr[i].rules[j];
checkRule = ruleObj.rule.split(':'); rule规则存在minLenth:6这样的校验
_rule = checkRule.shift(); 获取校验算法名称
checkRule.unshift(arr[i].el); checkRule首位存入校验的value值
checkRule.push(ruleObj.message); checkRule末尾加入校验的message
ruleMsg = rules[_rule].apply(null(ruleMsg) {
ruleMsg;
}
}
}
}
}
})();
ruleMsg;
}
}
}
},1)"> 添加规则
addRule: (ruleName,fn) {
rules[ruleName] = fn;
}
}
})();
validate.addRule('isAlphaNum',errorMsg) {
if (/[^a-zA-Z0-9]/.test(value)) {
errorMsg;
}
})
);
validate.addRule('isAlphaNum',errorMsg) {
.test(value)) {
errorMsg;
}
})
[{
el: registerForm.userName.value,rules: [{
rule: 'isNonEmpty'
},{
rule: 'minLength:3''isAlphaNum'
}]
},message: '密码不能为空''密码的长度不能小于6位''isMobile'
}]
}
]
(resultMsg) {
alert(resultMsg);
;
}
升级方案
if (!if (value.toString().length <if (value.toString().length >if (!/^\d{3}-d{8}|d{4}-d{7}|d{11}$/ errorMsg;
}
}
}
for (if (arr[i].el === (ruleMsg) {
ruleMsg;
}
}
}
},1)"> 校验所有接口
checkAll: var reusltMsg = [];
(ruleMsg) {
reusltMsg.push({
el: arr[i].el,rules: _rule,message: ruleMsg,alias: arr[i].alias 绑定一个别名用处:绑定到具体的一个DOM元素上显示错误信息
})
break; 跳出当前循环,不用把当前一个元素上多个验证不通过结果都存储起来
}
}
}
return reusltMsg.length > 0 ? reusltMsg : ;
},1)"> fn;
}
}
})();
>
/>
span class="error"></span>
style>
.error {
color: red;
}
>
'password' validate.checkAll(rulesArr);
(resultMsg) {
var re = 0,len = resultMsg.length; re < len; re++) {
var curResult = resultMsg[re];
var errorDom = document.querySelector('#registerForm p [name="'+curResult.alias+'"]').nextElementSibling;
errorDom.innerHTML = curResult.message;
}
;
}
兼容失去焦点的方案
* 校验方法
* @param {Object} vertifyObj 验证结构如:{userName:[{rule: 'isNonEmpty',{rule: 'minLength:3',message: '用户名长度不能小于3位'}}
* @param {Array} arr
* @return {*}
* (vertifyObj,arr) {
vertifyObj[arr[i].alias][j];
checkRule = ruleObj.rule.split(':'); 用户触发验证事件
trigger: (params) {
var self = ;
var key in params.rules) {
(params.rules.hasOwnProperty(key)) {
var requireEl = document.querySelector(params.el + ' [name="'+key+'"]');
params.rules[key];
var resultRules = rulesArr.filter((rule) {
if(!rule.trigger || rule.trigger === '') ;
(Array.isArray(rule.trigger)) {
return rule.trigger.indexOf('blur') > -1
} else {
return rule.trigger === 'blur';
}
}).map(function(rule){ JSON.parse(JSON.stringify(rule))});
((dom,curDomRules){
dom.addEventListener('blur',1)">(event){
var val = dom.value;
var ruleMsg = '';
) {
curDomRules[j];
var checkRule = ruleObj.rule.split(':'); rule规则存在minLenth:6这样的校验
var _rule = checkRule.shift(); 获取校验算法名称
checkRule.unshift(val); checkRule首位存入校验的value值
checkRule.push(ruleObj.message); checkRule末尾加入校验的message
ruleMsg = rules[_rule].apply( (ruleMsg) {
var errorDom = dom.nextElementSibling;
errorDom.innerHTML = ruleObj.message;
}
}
ruleMsg) {
dom.nextElementSibling;
errorDom.innerHTML = '';
}
},1)">);
})(requireEl,resultRules);
}
}
},1)"> fn;
}
}
})();
添加-自定义校验算法
validate.addRule('isAlphaNum',1)"> errorMsg;
}
})
{
userName: [
{rule: 'isNonEmpty',message: '用户名不能为空',trigger: 'blur'},{rule: 'minLength:3',message: '用户名长度不能小于3位',{rule: 'isAlphaNum',message: '用户名只能是数字跟字母的组合',1)">}
],password: [
{rule: 'isNonEmpty',message: '密码不能为空',{rule: 'minLength:6',message: '密码的长度不能小于6位',phoneNumber: [
{rule: 'isNonEmpty',message: '手机号不能为空',{rule: 'isMobile',message: '手机号码格式不正确',1)">}
]
}
validate.trigger({
el: '#registerForm'
},1)">
}
]
validate.checkAll(rules,rulesArr);
curResult.message;
}
;
}