ToolKit与jQuery类似的前端插件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ToolKit与jQuery类似的前端插件相关的知识,希望对你有一定的参考价值。
优点:
丢弃了一些不常用的方法(jQuery.fn):slideUp、fadeIn、animate等;
新增获取子节点的方法(ToolKit.fn):firstChild,lastChild等;
新增ToolKit.Threads线程操作函数(有效解决自定义弹窗同时运行的问题);
加入JSON对象(JSON.parse和JSON.stringify);
重写ToolKit.toString方法为JSON.stringify,ToolKit.get和ToolKit.post的dataType为json格式,使用更方便;
代码更小,但功能一样强大,选择器、异步取数和基本方法一个都不少,最重要的是逻辑清晰,初学者都可以进行二次开发。
(function(window) { var version = "1.1.1", arr = [], push = arr.push, slice = arr.slice, concat = arr.concat, indexOf = arr.indexOf || function(o, from) { var len = this.length, i = from ? from < 0 ? Math.max(0, len + from) : from : 0; for (; i < len; i++) { if (this[i] === o) { return i; } } return -1; }, support = {}, class2type = {}, toString = class2type.toString, hasOwn = class2type.hasOwnProperty, cssfix = ["Moz", "Webkit", "O", "ms"], cssform = { letterSpacing: "0", fontWeight: "400" }, csslock = { position: "absolute", visibility: "hidden", display: "block" }, rtrim = /^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, rsingleTag = /^<([\\w-]+)\\s*\\/?>(?:<\\/\\1>|)$/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:-]+)[^>]*)\\/>/gi, rmsPrefix = /^-ms-/, rdashAlpha = /-([\\da-z])/gi, fcamelCase = function(all, letter) { return letter.toUpperCase(); }, isArrayLike = function(o) { if (o == null) { return false; } var len = o.length, type = ToolKit.type(o); if (type === "function" || type === "string" || o.window === o || len == null) { return false; } return type === "array" || len === 0 || o.nodeType === 1 || (typeof len === "number") && (len - 1 in o); }, ToolKit = function(selector, context) { return new ToolKit.fn.init(selector, context); }; ToolKit.extend = function() { var key, value, length, isArray, configs, options, i = 1, limit = false, len = arguments.length, target = arguments[0]; if (typeof target === "boolean") { limit = target; target = arguments[i++] || {}; } if (typeof target !== "object" && typeof target !== "function" && typeof target !== "array") { target = {}; } for (; i < len; i++) { if (!!(options = arguments[i])) { for (key in options) { value = options[key]; configs = target[key]; if (value === configs || value === undefined) continue; if (limit && value && (ToolKit.isPlainObject(value) || (isArray = ToolKit.isArray(value)))) { target[key] = ToolKit.extend(limit, target[key] || (isArray ? [] : {}), value); } else { target[key] = value; } } } } return target; } ToolKit.improve = function() { var key, value, length, isArray, configs, options, i = 1, limit = false, len = arguments.length, target = arguments[0]; if (typeof target === "boolean") { limit = target; target = arguments[i++] || {}; } if (typeof target !== "object" && typeof target !== "function" && typeof target !== "array") { target = {}; } for (; i < len; i++) { if (!!(options = arguments[i])) { for (key in options) { value = options[key]; configs = target[key]; if (value === configs || value === undefined) continue; if (limit && value && (ToolKit.isPlainObject(value) || (isArray = ToolKit.isArray(value)))) { target[key] = ToolKit.improve(limit, target[key] || (isArray ? [] : {}), value); isArray = false; } else { target[key] = configs || value; } } } } return target; } ToolKit.extend(ToolKit, { kit: "kit", zIndex: 1000, type: function(o) { return o === null ? "null" : typeof o === "object" ? class2type[toString.call(o)] || "object" : typeof o; }, isString: function(o) { return ToolKit.type(o) === "string"; }, isFunction: function(o) { return ToolKit.type(o) === "function"; }, isArray: Array.isArray || function(obj) { return ToolKit.type(obj) === "array"; }, isNumber: function(o) { return !ToolKit.isArray(0) && Math.abs(o - parseFloat(o)) >= 0; }, isWindow: function(o) { return !!o && (o === o.window); }, inArray: function(o, list, from) { if (ToolKit.isArray(list)) { return indexOf.call(list, o, from); } return -1; }, isEmptyObject: function(o) { for (var i in o) { return false; } return true; }, isPlainObject: function(o) { if (!o || ToolKit.type(o) !== "object" || !!o.nodeType || ToolKit.isWindow(o)) { return false; } try { if (o.constructor && !hasOwn.call(o, "constructor") && !hasOwn.call(o.constructor.prototype, "constructor")) { return false; } } catch (e) { return false; } var key; for (key in o) {} return key === undefined || hasOwn.call(o, key); }, support: support }); ToolKit.extend(ToolKit, { error: function(msg) { throw new Error(msg); }, syntaxError: function(msg) { throw new SyntaxError(msg); } }); ToolKit.extend(ToolKit, { each: function(o, iterator, context) { var i = 0; if (isArrayLike(o)) { for (var len = o.length; i < len; i++) { if (iterator.call(context || o[i], i, o[i], o) === false) { break; } } } else { for (i in o) { if (iterator.call(context || o[i], i, o[i], o) === false) { break; } } } return o; }, map: function(o, iterator, context) { var val, i = 0, list = []; if (isArrayLike(o)) { for (var len = o.length; i < len; i++) { if ((val = iterator.call(context, o[i], i, o)) != null) list.push(val); } } else { for (i in o) { if ((val = iterator.call(context, o[i], i, o)) != null) list.push(val); } } return concat.apply([], list); }, merge: function(to, from) { var i = 0, l = +to.length || 0, len = (from && +from.length) || -1; while (i < len) { to[l++] = from[i++]; } if (len !== len) { while (from[i] !== undefined) { to[l++] = from[i++]; } } to.length = l; return to; }, makeArray: function(arr, results) { var r = results || []; if (arr != null) { if (isArrayLike(Object(arr))) { ToolKit.merge(r, typeof arr === "string" ? [arr] : arr); } else { push.call(r, arr); } } return r; } }); ToolKit.extend(ToolKit, { trim: function(string) { return string == null ? "" : String(string).replace(rtrim, ""); }, camelCase: function(string) { return String(string).replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); }, globalEval: function(code) { code = ToolKit.trim(code); if (code) { if (code.indexOf("use strict") > -1) { script = document.createElement("script"); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } else { (window.execScript || function(data) { window["eval"].call(window, data); })(code); } } }, htmlPrefilter: function(html) { return html.replace(rxhtmlTag, "<$1></$2>"); } }); var rtbody = /<tbody/i, rhtml = /<|&#?\\w+;/, rtagName = /<([\\w:]+)/, rleadingWhitespace = /^\\s+/, rscriptType = (/^$|\\/(?:java|ecma)script/i), whitespace = "[\\\\x20\\\\t\\\\r\\\\n\\\\f]", booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", wrapMap = { option: [1, "<select multiple=‘multiple‘>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], _default: support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, rwhitespace = new RegExp(whitespace + "+", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function buildFragment(elems, context, selection) { var elem, tmp, tag, wrap, index, counter, fragment = context.createDocumentFragment(), i = 0, list = [], len = elems.length; for (; i < len; i++) { elem = elems[i]; if (elem || elem === 0) { if (ToolKit.type(elem) === "object") { ToolKit.merge(list, elem.nodeType ? [elem] : elem); } else if (!rhtml.test(elem)) { list.push(context.createTextNode(elem)); } else { tmp = tmp || fragment.appendChild(context.createElement("div")); tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + ToolKit.htmlPrefilter(elem) + wrap[2]; index = wrap[0]; while (index--) { tmp = tmp.lastChild; } if (!support.leadingWhitespace && !!(counter = rleadingWhitespace.exec(this))) { list.push(context.createTextNode(counter[0])); } if (!support.tbody) { var xml = (tag === "table" && !rtbody.test(this)) ? tmp.firstChild : match[1] === "<table>" && !rtbody.test(this) ? tmp : 0; tbody = xml && xml.childNodes.firstChild; do { if (ToolKit.nodeName(tbody, "tbody") && !tbody.childNodes.length) { xml.removeChild(tbody); } } while (tbody && !!(tbody = tbody.nextSibling)); } ToolKit.merge(list, tmp.childNodes); tmp.textContent = ""; while (tmp.firstChild) { tmp.removeChild(tmp.firstChild); } tmp = fragment.lastChild; } } } if (tmp) { fragment.removeChild(tmp); } i = 0; while (!!(elem = list[i++])) { if (selection && ToolKit.inArray(elem, selection) !== -1) { continue; } fragment.appendChild(elem); } return fragment; }; ToolKit.extend(ToolKit, { parse: function(text, reviver) { return window.JOSN.parse(text, reviver); }, toString: function(value, replacer, space) { return window.JOSN.stringify(value, replacer, space); }, parseHTML: function(data, context) { if (!data || typeof data !== "string") { return null; } context = context || document; var html = rsingleTag.exec(data); if (html) { return [context.createElement(html[1])]; } html = buildFragment([data], context); return ToolKit.merge([], html.childNodes); } }); ToolKit.each(["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Error", "Object", "Document", "Symbol"], function() { class2type["[object " + this + "]"] = this.toLowerCase(); }); (function($) { var cx = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g, escapable = /[\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g, indent, iterator, target = ‘‘, meta = { ‘\\b‘: ‘\\\\b‘, ‘\\t‘: ‘\\\\t‘, ‘\\n‘: ‘\\\\n‘, ‘\\f‘: ‘\\\\f‘, ‘\\r‘: ‘\\\\r‘, ‘"‘: ‘\\\\"‘, ‘\\\\‘: ‘\\\\\\\\‘ }; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? ‘"‘ + string.replace(escapable, function(a) { var c = meta[a]; return typeof c === ‘string‘ ? c : ‘\\\\u‘ + (‘0000‘ + a.charCodeAt(0).toString(16)).slice(-4); }) + ‘"‘ : ‘"‘ + string + ‘"‘; } function str(key, holder) { var i, // The loop counter. k, // The member key. v, // The member value. length, mind = target, partial, value = holder[key]; if (value && $.isFunction(value.toJSON)) { value = value.toJSON(key); } if ($.isFunction(iterator)) { value = iterator.call(holder, key, value); } switch (typeof value) { case ‘string‘: return quote(value); case ‘number‘: return isFinite(value) ? String(value) : ‘null‘; case ‘boolean‘: case ‘null‘: return String(value); case ‘object‘: if (!value) { return ‘null‘; } target += indent; partial = []; if ($.isArray(value)) { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || ‘null‘; } v = partial.length === 0 ? ‘[]‘ : target ? ‘[\\n‘ + target + partial.join(‘,\\n‘ + target) + ‘\\n‘ + mind + ‘]‘ : ‘[‘ + partial.join(‘,‘) + ‘]‘; target = mind; return v; } if (iterator && typeof iterator === ‘object‘) { length = iterator.length; for (i = 0; i < length; i += 1) { if (typeof iterator[i] === ‘string‘) { k = iterator[i]; v = str(k, value); if (v) { partial.push(quote(k) + (target ? ‘: ‘ : ‘:‘) + v); } } } } else { for (k in value) { if (hasOwn.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (target ? ‘: ‘ : ‘:‘) + v); } } } } v = partial.length === 0 ? ‘{}‘ : target ? ‘{\\n‘ + target + partial.join(‘,\\n‘ + target) + ‘\\n‘ + mind + ‘}‘ : ‘{‘ + partial.join(‘,‘) + ‘}‘; target = mind; return v; } } if (!$.isFunction(Date.prototype.toJSON)) { function f(n) { return n < 10 ? ‘0‘ + n : n; } Date.prototype.toJSON = function(key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + ‘-‘ + f(this.getUTCMonth() + 1) + ‘-‘ + f(this.getUTCDate()) + ‘T‘ + f(this.getUTCHours()) + ‘:‘ + f(this.getUTCMinutes()) + ‘:‘ + f(this.getUTCSeconds()) + ‘Z‘ : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key) { return this.valueOf(); }; } $.improve(window.JSON = window.JSON || {}, { parse: function(text, reviver) { var j, walk = function(holder, key) { var k, v, value = holder[key]; if (value && typeof value === ‘object‘) { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function(a) { return ‘\\\\u‘ + (‘0000‘ + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\\],:{}\\s]*$/.test( text.replace(/\\\\(?:["\\\\\\/bfnrt]|u[0-9a-fA-F]{4})/g, ‘@‘) .replace(/"[^"\\\\\\n\\r]*"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g, ‘]‘) .replace(/(?:^|:|,)(?:\\s*\\[)+/g, ‘‘) )) { j = eval(‘(‘ + text + ‘)‘); return $.isFunction(reviver) ? walk({ ‘‘: j }, ‘‘) : j; } $.error(‘JSON.parse‘); }, stringify: function(value, replacer, space) { var i; indent = ‘‘; iterator = ‘‘; if ($.isNumber(space)) { for (i = 0; i < space; i += 1) { indent += ‘ ‘; } } else if ($.isString(space)) { indent = space; } iterator = replacer; if ( replacer && !$.isFunction(replacer) && (typeof replacer !== ‘object‘ || typeof replacer.length !== ‘number‘) ) { $.error(‘JSON.stringify‘); } return str(‘‘, { ‘‘: value }); } }); })(ToolKit); var sortInput, hasDuplicate; var documentElement = document.documentElement; var rnative = /^[^{]+\\{\\s*\\[native \\w/; var check = function(tag, callbak) { if (arguments.length === 1) { callbak = tag; tag = "div"; } var elem = document.createElement(tag); try { return !!callbak(elem); } catch (e) { return false; } finally { if (elem.parentNode) { elem.parentNode.removeChild(elem); } elem = null; } }; if (rnative.test(document.getElementsByClassName)) { support.getElementsByClassName = check(function(div) { div.innerHTML = "<div class=‘a‘></div><div class=‘a i‘></div>"; div.firstChild.className = "i"; return div.getElementsByClassName("i").length === 2; }); } if (rnative.test(document.querySelectorAll)) { support.querySelectorAll = true; var rquerySelectorAll = []; check(function(div) { div.innerHTML = "<select msallowclip=‘‘><option selected=‘‘></option></select>"; if (div.querySelectorAll("[msallowclip^=‘‘]").length) { rquerySelectorAll.push("[*^$]=" + whitespace + "*(?:‘‘|\\"\\")"); } if (!div.querySelectorAll("[selected]").length) { rquerySelectorAll.push("\\\\[" + whitespace + "*(?:value|" + booleans + ")"); } if (!div.querySelectorAll(":checked").length) { rquerySelectorAll.push(":checked"); } }); check(function(div) { var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.id = "B"; div.appendChild(document.createElement("div").appendChild(document.createElement("a"))); div.appendChild(input).setAttribute("name", "D"); if (div.querySelectorAll("[name=d]").length || !div.querySelectorAll("[name=D]").length) { rquerySelectorAll.push("name" + whitespace + "*[*^$|!~]?="); } if (div.querySelectorAll("input[id=‘b‘]").length || !div.querySelectorAll("input[id=‘B‘]").length) { rquerySelectorAll.push("id" + whitespace + "*[*^$|!~]?="); } if (!div.querySelectorAll(":enabled").length) { rquerySelectorAll.push(":enabled", ":disabled"); } div.querySelectorAll("*,:x"); rquerySelectorAll.push(",.*:"); }); check(function(div) { documentElement.appendChild(div).innerHTML = "<a id=‘toolkit‘></a>" + "<select id=‘toolkit-\\r\\\\‘ msallowcapture=‘‘>" + "<option selected=‘‘></option></select>"; if (div.querySelectorAll("[msallowcapture^=‘‘]").length) { rquerySelectorAll.push("[*^$]=" + whitespace + "*(?:‘‘|\\"\\")"); } if (!div.querySelectorAll("[selected]").length) { rquerySelectorAll.push("\\\\[" + whitespace + "*(?:value|" + booleans + ")"); } if (!div.querySelectorAll("[id~=toolkit-]").length) { rquerySelectorAll.push("~="); } if (!div.querySelectorAll(":checked").length) { rquerySelectorAll.push(":checked"); } if (!div.querySelectorAll("a#toolkit+*").length) { rquerySelectorAll.push(".#.+[+~]"); } }); support.rquerySelectorAll = !rquerySelectorAll.length || new RegExp(rquerySelectorAll.join("|")); } if (rnative.test((support.matches = documentElement.matches || documentElement.webkitMatchesSelector || documentElement.mozMatchesSelector || documentElement.oMatchesSelector || documentElement.msMatchesSelector))) { support.matchesSelector = true; check(function(div) { var matchesSelector = []; support.disConnectedMatch = support.matches.call(div, "div"); matches.call(div, "[s!=‘‘]:x"); matchesSelector.push("!=", extensions); support.rmatchesSelector = new RegExp(matchesSelector.join("|")); }); } support.getElementById = check(function() { document.documentElement.appendChild(div).id = "test"; if (document.getElementById) { return !document.getElementsByName || !document.getElementsByName("test").length; } }); support.getElementsByTagName = check(function(div) { div.appendChild(document.createComment("")); return !div.getElementsByTagName("*").length; }); check("form", function(form) { support.enctype = !!form.enctype; }); check("input", function(input) { input.type = "checkbox"; support.checkOn = input.value !== ""; input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; }); check("select", function(select) { var option = select.appendChild(document.createElement("option")); select.disabled = true; support.optionSelected = option.selected; support.optionDisabled = !option.disabled; }); check(function(div) { var a, t, style, input; div.setAttribute("className", "t"), div.innerHTML = " <link/><table></table><a href=‘/a‘>a</a><input type=‘checkbox‘/><!--<span></span>-->"; a = (t = div.getElementsByTagName("a")) ? t[0] : null; input = (t = div.getElementsByTagName("input")) ? t[0] : {}; style = a && a.style; if (!style) { return; } support.leadingWhitespace = div.firstChild.nodeType === 3; support.leadingAnnotation = div.lastChild.nodeType === 8; support.tbody = !div.getElementsByTagName("tbody").length; support.htmlSerialize = !!div.getElementsByTagName("link").length; support.html5Clone = document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>"; support.attr = div.className !== "t"; style.cssText = "float:left;opacity:.5;top:1px"; support.opacity = style.opacity === "0.5"; support.cssFloat = !!style.cssFloat; support.style = /top/.test(a.getAttribute("style")); support.hrefNormalized = a.getAttribute("href") === "/a"; }); check(function(div) { var i, len, value, target, style = div.style, list = ["boxSizing", "boxShadow", "animation", "transition", "transform", "transformOrigin", "transitionDelay", "filter"]; checking = function(t) { if (t in style) return true; target = t.charAt(0).toUpperCase() + t.slice(1); for (var i = 0, len = cssfix.length; i < len; i++) { if ((cssfix[i] + target) in style) { return true; } } return false; }; for (i = 0, len = list.length; i < len; i++) { value = list[i]; support[value] = checking(value) } for (i in { submit: true, change: true, focusin:
以上是关于ToolKit与jQuery类似的前端插件的主要内容,如果未能解决你的问题,请参考以下文章