javascript 常用函数

Posted SunsCheung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 常用函数相关的知识,希望对你有一定的参考价值。

/***javascript 常用函数**/
function
each( object, callback ) { if ( undefined === object.length ){ for ( var name in object ) { if (false === callback( object[name], name, object )) break; } } else { for ( var i = 0, len = object.length; i < len; i++ ) { if (i in object) { if (false === callback( object[i], i, object )) break; } } } } //过滤空白文本节点 function filterSpaceNode(nodes) {掉 var ret=[]; for(var i=0;i<nodes.length;i++) { if (nodes[i].nodeType===3 && /^\s+$/.test(nodes[i].nodeValue)) { continue; } ret.push(nodes[i]); } return ret; } function addClassName(obj,cn) { return obj.className += " " + cn; } function delClassName(obj,cn) { return obj.className = obj.className.replace(new RegExp("\\b"+cn+"\\b"),""); //同样,多个className之间的多个空格也会被视为一个 } function hasClassName(obj,cn) { return (new RegExp("\\b"+cn+"\\b")).test(obj.className); } function placeNode(node,fn,__this) { fn.call(__this,frag(node)); return __this; } function append(node, newNode) { return placeNode(newNode,function (one) {node.appendChild(one)},node); } function preappend(node, newNode) { return placeNode(newNode,function (one) {node.insertBefore(one,node.firstChild)},node); } function before(node, newNode) { return placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node)},node); } function after(node, newNode) { //如果node有下一个节点的话,newNode 插入到node.nextSibling的前面 //如果node没有下一个节点,newNode插入为node.parentNode的最后一个子 if (node.nextSibling) { placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node.nextSibling)},node); } else { placeNode(newNode,function (one) {node.parentNode.appendChild(one)},node); } return node; } //如果新节点是页面中已经存在的则新节点原来的位置会消失 function replaceNode(newNode, node) { node.parentNode.replaceChild(newNode, node); } function delNode(node) { node.parentNode.removeChild(this); } function frag(nodes) { var tempFrag =document.createDocumentFragment(); if (nodes.nodeType) {nodes=[nodes];} /* 错误的写法 传入的是引用 each(nodes,function(node){ tempFrag.appendChild(node); })*/ for(var i=0;i<nodes.length;i++) { //克隆后不在是引用 var a = nodes[i].cloneNode(true); (function(node){ tempFrag.appendChild(node); })(a) } /* while(nodes.length>0) { tempFrag.appendChild(nodes[0]); alert(nodes.length); } */ return tempFrag; } //html转换为对象 function html2Obj(html) { var div = document.createElement(‘div‘); div.innerHTML = html; return div.firstChild; } //数据的本地化存储,都兼容 function makeWebStorage() { //ie用userdata实现,w3c浏览器本身支持 if (!("localStorage" in window)) { var store = { userData : null, name : location.hostname, init : function () { if (!store.userData) { try { store.userData = document.createElement(‘INPUT‘); store.userData.type = "hidden"; store.userData.style.display = "none"; store.userData.addBehavior("#default#userData"); document.body.appendChild(store.userData); var expires = new Date(); expires.setDate(expires.getDate() + 365); store.userData.expires = expires.toUTCString(); } catch (e) { return false; } } return true; }, setItem : function (key, value) { if (store.init()) { store.userData.load(store.name); store.userData.setAttribute(key, value); store.userData.save(store.name); } }, getItem : function (key) { if (store.init()) { store.userData.load(store.name); return store.userData.getAttribute(key) } }, remove : function (key) { if (store.init()) { store.userData.load(store.name); store.userData.removeAttribute(key); store.userData.save(store.name); } } }; }else{ store = { set:function(key, value){localStorage.setItem(key, value)}, get:function(key){return localStorage.getItem(key)}, remove:function(key){return localStorage.removeItem(key)} } } window.webStorage = store; } /** * 记录函数调用的次数 */ function invokeTimes(){ if(arguments.callee.times == undefined) { arguments.callee.times = 0; } arguments.callee.times ++; console.log(arguments.callee.times); } document.body.onclick = function(){ invokeTimes(); } //变量定义 效果同php中的define函数 function define (name, value) { // Define a new constant // // version: 903.3016 // discuss at: http://phpjs.org/functions/define // + original by: Paulo Freitas // + revised by: Andrea Giammarchi (http://webreflection.blogspot.com) // + reimplemented by: Brett Zamir (http://brett-zamir.me) // * example 1: define(‘IMAGINARY_CONSTANT1‘, ‘imaginary_value1‘); // * results 1: IMAGINARY_CONSTANT1 === ‘imaginary_value1‘ var defn, replace, script, that = this, d = this.window.document; var toString = function (name, value) { return ‘const ‘ + name + ‘=‘ + (/^(null|true|false|(\+|\-)?\d+(\.\d+)?)$/.test(value = String(value)) ? value : ‘"‘ + replace(value) + ‘"‘); }; try { eval(‘const e=1‘); replace = function (value) { var replace = { "\x08": "b", "\x0A": "\\n", "\x0B": "v", "\x0C": "f", "\x0D": "\\r", ‘"‘: ‘"‘, "\\": "\\" }; return value.replace(/\x08|[\x0A-\x0D]|"|\\/g, function (value) { return "\\" + replace[value]; }); }; defn = function (name, value) { if (d.createElementNS) { script = d.createElementNS(‘http://www.w3.org/1999/xhtml‘, ‘script‘); } else { script = d.createElement(‘script‘); } script.type = ‘text/javascript‘; script.appendChild(d.createTextNode(toString(name, value))); d.documentElement.appendChild(script); d.documentElement.removeChild(script); }; } catch (e) { replace = function (value) { var replace = { "\x0A": "\\n", "\x0D": "\\r" }; return value.replace(/"/g, ‘""‘).replace(/\n|\r/g, function (value) { return replace[value]; }); }; defn = (this.execScript ? function (name, value) { that.execScript(toString(name, value), ‘VBScript‘); } : function (name, value) { eval(toString(name, value).substring(6)); }); } defn(name, value); } /** * 根据类名获取元素 * * @param className * @param context * @returns */ function getByClassName(className,context) { context=context || document; if (context.getElementsByClassName) { return context.getElementsByClassName(className); } var nodes=context.getElementsByTagName(‘*‘),ret=[]; for (var i=0;i<nodes.length;i++) { if (nodes[i].nodeType == 1 && nodes[i].className.indexOf(className) != -1) { ret.push(nodes[i]); } } return ret; } /** * Registers a callback for DOM ready. If DOM is already ready, the * callback is called immediately. * @param {Function} Array callback */ function domReady(callback) { var isTop, testDiv, scrollIntervalId, isPageLoaded = false, doc = document, readyCalls = []; function runCallbacks(callbacks) { var i; for (i = 0; i < callbacks.length; i += 1) { callbacks[i](doc); } } function callReady() { var callbacks = readyCalls; if (isPageLoaded) { //Call the DOM ready callbacks if (callbacks.length) { readyCalls = []; runCallbacks(callbacks); } } } /** * Sets the page as loaded. */ function pageLoaded() { if (!isPageLoaded) { isPageLoaded = true; if (scrollIntervalId) { clearInterval(scrollIntervalId); } callReady(); } } if (document.addEventListener) { //Standards. Hooray! Assumption here that if standards based, //it knows about DOMContentLoaded. document.addEventListener("DOMContentLoaded", pageLoaded, false); window.addEventListener("load", pageLoaded, false); } else if (window.attachEvent) { window.attachEvent("onload", pageLoaded); testDiv = document.createElement(‘div‘); try { isTop = window.frameElement === null; } catch (e) {} //DOMContentLoaded approximation that uses a doScroll, as found by //Diego Perini: http://javascript.nwbox.com/IEContentLoaded/, //but modified by other contributors, including jdalton if (testDiv.doScroll && isTop && window.external) { scrollIntervalId = setInterval(function () { try { testDiv.doScroll(); pageLoaded(); } catch (e) {} }, 1); } } //Check if document already complete, and if so, just trigger page load //listeners. Latest webkit browsers also use "interactive", and //will fire the onDOMContentLoaded before "interactive" but not after //entering "interactive" or "complete". More details: //http://dev.w3.org/html5/spec/the-end.html#the-end //http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded //Hmm, this is more complicated on further use, see "firing too early" //bug: https://github.com/requirejs/domReady/issues/1 //so removing the || document.readyState === "interactive" test. //There is still a window.onload binding that should get fired if //DOMContentLoaded is missed. if (document.readyState === "complete") { pageLoaded(); } if (isPageLoaded) {//dom已经ready callback(doc); } else { readyCalls.push(callback); } } domReady(function(){ alert(‘domload‘); alert(document.getElementById(‘container‘)); }) //改变某个函数的内部this指针 function closure(fn, scope) { return function (){ fn.apply(scope, arguments); }; } //调用某个对象的某个函数,并将次对象作为方法的作用域 function invoke(obj, methodName) { return function(){ obj.methodName.apply(obj, arguments); }; } // 元素数据缓存 (function(){ var cache = [0],expando = ‘data‘ + +new Date(); function data(elem) { var cacheIndex = elem[expando], nextCacheIndex = cache.length; if(!cacheIndex) { cacheIndex = elem[expando] = nextCacheIndex; cache[cacheIndex] = {}; } return { get : function(key) { if(typeof key === ‘string‘) { return cache[cacheIndex] ? cache[cacheIndex][key] : null; } return cache[cacheIndex] ? cache[cacheIndex] : null; }, set : function(key, val) { cache[cacheIndex][key] = val; return data(elem); }, remove : function(key){ if(cache[cacheIndex]) { return cache.splice(cacheIndex,1); } } } } window.data = data; })(); //js请求xml文件, if (window.ActiveXObject) { //IE var getXMLDOM=function () { return new ActiveXObject("Microsoft.XmlDom"); },loadXMLFile=function (xmlDom,url,callback) { xmlDom.onreadystatechange=function () { if (xmlDom.readyState===4) { if (xmlDom.parseError.errorCode===0) { callback.call(xmlDom); } else { throw new Error("XML Parse Error:"+xmlDom.parseError.reason); } } }; xmlDom.load(url); return xmlDom; },loadXMLString=function (xmlDom,s) { xmlDom.loadXML(s); if (xmlDom.parseError.errorCode!==0) { throw new Error("XML Parse Error:"+xmlDom.parseError.reason); } return xmlDom; }, getXML=function (xmlNode) { return xmlNode.xml; }; }else if (document.implementation && document.implementation.createDocument) { //W3C var getXMLDOM=function () {//获取一个XMLDOM对象 return document.implementation.createDocument("","",null); }, loadXMLFile=function (xmlDom,url,callback) { if (xmlDom.async===true) { xmlDom.onload=function () { if (xmlDom.documentElement.nodeName=="parsererror") { throw new Error("XML Parse Error:"+xmlDom.documentElement.firstChild.nodeValue); } else { callback.call(xmlDom); } }; } console.dir(xmlDom); xmlDom.load(url); return xmlDom; }, loadXMLString=function (xmlDom,s) { var p = new DOMParser(); var newDom=p.parseFromString(s,"text/xml"); if (newDom.documentElement.nodeName=="parsererror") { throw new Error("XML Parse Error:"+newDom.documentElement.firstChild.nodeValue); } while (xmlDom.firstChild) { xmlDom.removeChild(xmlDom.firstChild); } for (var i=0,n;i<newDom.childNodes.length;i++) { n=xmlDom.importNode(newDom.childNodes[i],true); //importNode用于把其它文档中的节点导入到当前文档中 //true参数同时导入子节点 xmlDom.appendChild(n); } return xmlDom; }, getXML=function (xmlNode) { var s= new XMLSerializer(); return s.serializeToString(xmlNode,"text/xml"); }; } var xmldom = getXMLDOM(); loadXMLFile(xmldom,"/xml.php",function () { alert(this); }); /** args { url method 默认值为get success Function data {key:value} cache Boolean true表示缓存,默认值为false datatype 默认 text text|xml } */ function ajax(args) { //创建xhr对象 function createXHR() { return window.XMLHttpRequest? new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");//IE6 } //拼接参数 function params(o) { var a=[]; for (var i in o) { a.push(encodeURIComponent(i)+"="+encodeURIComponent(o[i])); } return a.join("&"); } var xhr = createXHR(); args.method=args.method || "get"; if (!args.cache) { args.data.cache = (new Date()*1); } var data_str = params(args.data) if (/get/i.test(args.method) && data_str) { args.url += args.url.indexOf("?")<0 ? ‘?‘ : ‘&‘; args.url += data_str; } xhr.open(args.method,args.url,true); xhr.onreadystatechange=function () { if (xhr.readyState===4 && xhr.status===200) { if(!args.datatype || args.datatype.toLowerCase() === ‘text‘) { args.success(xhr.responseText); }else{ args.success(xhr.responseXML); } } }; if (/post/i.test(args.method)) { xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(data); } else { xhr.send(); } } ajax({ url:"/xml.php", method:‘post‘, success:function(xmldom){ alert(xmldom.nodeName); }, data:{id:1}, datatype:‘xml‘ }) //计算数组中的最大值 Array.prototype.max = function(){ return Math.max.apply({},this) } //计算数组中的最小值 Array.prototype.min = function(){ return Math.min.apply({},this) } //复制数组 Array.prototype.copy = function() { return [].concat(this); }; //去除数组中只指定元素,只能去除一个,如果想多个,之前先用unique处理 Array.prototype.remove = function(value){ for(var i=0,len=this.length;i<len;i++) { if(this[i]==value){ this.splice(i, 1); break; } } return this; } //去除数组中只指定元素,只能去除一个,如果想多个,之前先用unique处理 Array.prototype.inArray = function(value){ var index = -1; each(this,function(v,k){ if(v == value){ index = k; return false; } }) return index; } //去除数组中的重复元素 Array.prototype.unique = function(){ var rst = []; each(this, function(v,k){ if(rst.inArray(v)<0) rst.push(v); }) return rst; } String.prototype.repeat=function(n){return new Array(n+1).join(this);} String.prototype.ltrim=function(){return this.replace(/^\s*/, "");} String.prototype.rtrim=function(){return this.replace(/\s*$/, "");} String.prototype.trim=function(){return this.rtrim().ltrim();} //非ascii字符 String.prototype.hasChinese=function(){return /[^\u00-\uff]/g.test(this);} //包括中英韩文,这三种语言里面有更多共同的 String.prototype.onlyChinese=function(){return /^[\u0391-\u9FBF]+$/g.test(this);} //取得字符串实际长度(汉字算两个字节,英文字母算一个字节) \x代表ascii码,会按unicode码进行匹配 String.prototype.bytes=function(){ return this.replace(/[^\x00-\xff]/gi,‘xx‘).length;} Number.prototype.inter=function (a,b) {//检测数字是否在区间之内 var min=Math.min(a,b),max=Math.max(a,b); return this==a || this==b || (Math.max(this,min)==this && Math.min(this,max)==this); };   

 

以上是关于javascript 常用函数的主要内容,如果未能解决你的问题,请参考以下文章

javascript JS-常用代码片段

javascript常用代码片段

markdown Snippets.md是我最常用的HTML,CSS和JavaScript代码片段,用于前端Web开发

C#常用代码片段备忘

18个常用的JavaScript片段分享

21个常用代码片段