仿jQuery完成之前自己的小插件整合
要查看我的其他小插件,获取节点,发送ajax等可以点击https://blog.csdn.net/weixin_43659627
;(function (global, obj, otherFunc) {
global.$ = global.JBest = obj || '';
otherFunc();
})(this, {
/**
*post和put请求默认发送FormData数据
* 传入回调则将err和response给callback
* 没有回调则为Promise实例
* */
/**
*
* @param url: string *required
* @param options: object
* @param callback: function
*/
ajax: function (url, options, callback) {
const error = function (msg) {
throw new Error(msg);
};
const xml = window.XMLHttpRequest ?
new XMLHttpRequest() :
new ActiveXObject("Microsoft.XMLHTTP");
if (url instanceof String) {
error.call(this, 'ajax method required url!');
}
const header = options.header || {};
const data = options.data || {};
const method = options.method.toLowerCase() || 'post';
const asyncRequest = options.async || true;
const headerKey = Object.keys(header);
const headerValue = Object.values(header);
const dataKey = Object.keys(data);
const dataValue = Object.values(data);
//request => xml
const parseHeader = function (request) {
for (let i = 0; i < headerKey.length; i++) {
request.setRequestHeader(headerKey[i], headerValue[i]);
}
};
const parseDataToBody = function () {
let form = new FormData();
for (let i = 0; i < dataKey.length; i++) {
form.append(dataKey[i], dataValue[i]);
}
return form;
};
const parseDataToUrl = function () {
let str = '?';
for (let i = 0; i < dataKey.length; i++) {
str += dataKey[i] + '=' + dataValue[i] + '&'
}
str = str.slice(0, str.length - 1);
return url + str;
};
if (callback) {
try {
if (method === 'get' || method === 'delete') {
xml.open(method, parseDataToUrl(method), asyncRequest);
parseHeader(xml);
xml.send(null);
} else {
xml.open(method, url, asyncRequest);
parseHeader(xml);
xml.send(parseDataToBody());
}
xml.onreadystatechange = function () {
if (xml.status === 200 && xml.readyState === 4) {
try {
resolve(JSON.parse(xml.responseText));
}catch (e) {
resolve(xml.responseText);
}
}
}
} catch (e) {
callback(e);
}
} else {
return new Promise((resolve, reject) => {
try {
if (method === 'get' || method === 'delete') {
xml.open(method, parseDataToUrl(method), asyncRequest);
parseHeader(xml);
xml.send(null);
} else {
xml.open(method, url, asyncRequest);
parseHeader(xml);
xml.send(parseDataToBody());
}
xml.onreadystatechange = function () {
if (xml.status === 200 && xml.readyState === 4) {
try {
resolve(JSON.parse(xml.responseText));
}catch (e) {
resolve(xml.responseText);
}
}
}
} catch (e) {
reject(e);
}
})
}
},
/**
* 获取节点,传入选择器,支持id class 标签
* @param option: id/class
* @return {HTMLElement|HTMLCollectionOf<HTMLElementTagNameMap[*]>|HTMLCollectionOf<Element>}
*/
getNode: function (options) {
let str = options;
if (!str)
$.error.call(this, '传入参数不合法 illegal options you provided ');
if (str.startsWith('.'))
return document.getElementsByClassName(options.slice(1, options.length));
else if (str.startsWith('#'))
return document.getElementById(options.slice(1, options.length));
else
return document.getElementsByTagName(options);
},
/**
* 根据传入的选择器删除相应的节点
* args 支持的类型:id class tag Array
* Array 中必须以id或者标签或者class为值,利用递归删除,将多个节点的情况拆分单个节点进行删除
* */
remove: (args) => {
if (!args)
$.error.call(this, `remove() needs a selector < class id tag > remove方法需要提供标签或者标签id或者标签class`);
/**
* 如果传入的数组,则进行拆分,对每一个值查找到的节点进行删除
* 利用递归进行删除
* */
if (args instanceof Array) {
for (let i in args) {
$.remove(args[i]);
}
} else {
let node = $.getNode(args);
/**
* 如果根据class或者标签(本质为节点数组)
*/
if (node instanceof HTMLCollection) {
for (let i = 0; i < node.length + 1; i++) {
if (!node[i])
$.error.call(this, 'no such selector < class id tag > 没有找到提供的节点');
node[i].parentNode.removeChild(node[i]);
}
}
/**
* 如果根据id查找的(不是节点数组)
*/
else if (node) {
if (!node)
$.error.call(this, 'no such selector < class id tag > 没有找到提供的选择器的节点');
node.parentNode.removeChild(node);
} else
$.error.call(this, '传入的标签或者标签id或者标签class查询不到值 cant find node by the selector < class id tag > you provided');
}
},
/**
*
*/
Event: function(){
let events = {};
let args = {};
/**
*
* @param flag: String
* @param options: any
*/
this.emit = function (flag, options) {
Object.defineProperty(args, flag, {
value: options,
enumerable: true,
configurable: true,
writable: true
});
if (events[flag])
events[flag].call(this, args[flag]);
else
Object.defineProperty(events, flag, {
value: function () {
},
enumerable: true,
configurable: true,
writable: true
});
};
/**
*
* @param flag: String
* @param callback: Function
*/
this.on = function (flag, callback) {
if (!events[flag])
Object.defineProperty(events, flag, {
value: callback,
configurable: true,
writable: true,
enumerable: true
});
else {
events[flag] = callback;
events[flag].call(this, args[flag]);
}
}
},
/**
*统一处理错误信息
*/
error: function (msg) {
throw new Error(msg);
},
/**
*
* @param parentNode : String : id or class
* @param childNode : String : tag name
* @param options : Object
*/
append: function (parentNode, childNode, options) {
let parent = !(parentNode instanceof HTMLElement) ?
parentNode.startsWith('#') ?
$.getNode(parentNode) :
$.getNode(parentNode)[0] :
parentNode;
let child = document.createElement(childNode);
let keys = Object.keys(options);
let values = Object.values(options);
for (let i = 0; i < keys.length; i++) {
child[keys[i]] = values[i];
}
parent.appendChild(child);
}
}, function () {
/**
*
* @param rule: <'number'|'letter'|'email'|'phone'|'w'|'w_'|'w:_'>
* @return Boolean
*/
HTMLInputElement.prototype.verifyRule = function (rule) {
let that = this;
let rules = {
'number': function () {
return /^[0-9]+$/;
},
'letter': function () {
return /^[a-zA-Z]+$/;
},
'email': function () {
return /^[0-9a-zA-Z_]+@[0-9a-zA-Z.]+[0-9a-zA-Z]$/;
},
'phone': function () {
return /^((\+86)?(13\d|14[5-9]|15[0-35-9]|166|17[0-8]|18\d|19[8-9])\d{8})$/;
},
'w': function () {
return /^[0-9a-zA-Z]+$/;
},
'w_': function () {
return /^[0-9a-zA_Z_]+$/;
},
'w:_': function () {
return /^[0-9a-zA-Z:_]+$/;
}
};
return rules[rule]().test(that.value);
};
/**
*
* @param target:节点
* @param callback:传递的方法,回调
* @param flag?false:flag :是否冒泡
*/
HTMLElement.prototype.addEvent = function (target, callback, flag) {
if (addEventListener) {
return this.addEventListener(target, callback, flag ? false : flag);
} else
return this.attachEvent(`on${target}`, callback, flag ? false : flag);
};
/**
*
* @param childNode: String
* @param options: Object
*/
HTMLElement.prototype.appendWith = function (childNode, options) {
$.append.apply($, [this, childNode, options]);
}
});
欢迎留言交流~