最常用的10个javascript自定义函数

javascript|函数

If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today.

Upon further reading this article, it is suggested that for this article in particular the reader should use an alternate style with cleaner whitespace and larger margins. This is available by selecting Clean with Whitespace available on the side bar.

10) addEvent()

Surely a staple to event attachment! Regardless to what version you use written by whatever developer, it does what it says it does. And of course as you might of known, I’ve put together quite a handy version myself recently of addEvent() with some help from the contest winner and Mark Wubben along with a few minor syntax adjustments. But just to be fair to Scott Andrew, here is the original that started it all.

Scott Andrew’s original addEvent() function

function addEvent(elm, evType, fn, useCapture) {if (elm.addEventListener) {elm.addEventListener(evType, fn, useCapture);return true;}else if (elm.attachEvent) {var r = elm.attachEvent('on' + evType, fn);return r;}else {elm['on' + evType] = fn;}}

9) addLoadEvent()

Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it’s supposed to, and does it well.

addLoadEvent() by Simon Willison

function addLoadEvent(func) {var oldonload = window.onload;if (typeof window.onload != 'function') {window.onload = func;}else {window.onload = function() {oldonload();func();}}}

Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:

assigning multiple load events to window

addEvent(window,'load',func1,false);addEvent(window,'load',func2,false);addEvent(window,'load',func3,false);

8) getElementsByClass()

Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had a crack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer’s surprise, it’s not an original DOM method as one might think…afterall, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:

getElementsByClass by Dustin Diaz

function getElementsByClass(searchClass,node,tag) {var classElements = new Array();if ( node == null )node = document;if ( tag == null )tag = '*';var els = node.getElementsByTagName(tag);var elsLen = els.length;var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");for (i = 0, j = 0; i < elsLen; i++) {if ( pattern.test(els[i].className) ) {classElements[j] = els[i];j++;}}return classElements;}

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

7) cssQuery()

Originally written by Dean Edwards as a way to query the DOM according to CSS properties which supports a multitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC lisencing) I won’t post it on this site. Full documentation can be found on the myCssQuery reference and download page.

6) toggle()

To be totally honest, there are probably more variations of this function than there needs to be. The history of ‘toggling’ basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.

toggle() by the masses

function toggle(obj) {var el = document.getElementById(obj);if ( el.style.display != 'none' ) {el.style.display = 'none';}else {el.style.display = '';}}

5) insertAfter()

As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn’t. So rather than pulling the function straight out of the book, I’ll leave that up to you to buy it yourself. Instead I’ve pulled this simple method from public domain:

insertAfter() on public domain

function insertAfter(parent, node, referenceNode) {parent.insertBefore(node, referenceNode.nextSibling);}

4) inArray()

This too is very sad that this isn’t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn’t quite a function; it’s a prototype that extends the DOM Array object. I remember one day thinking to myself “surely I can do this in PHP, it’s gotta be in JavaScript.” Well, this extension makes it work just like you’d expect if you’re a PHP developer. Here is a version from EmbiMEDIA

inArray Prototype Array object by EmbiMedia

Array.prototype.inArray = function (value) {var i;for (i=0; i < this.length; i++) {if (this[i] === value) {return true;}}return false;};

3, 2, & 1) getCookie(), setCookie(), deleteCookie()

I honestly don’t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it’s so easy, and it’s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.

getCookie(), setCookie(), deleteCookie() open domain

function getCookie( name ) {var start = document.cookie.indexOf( name + "=" );var len = start + name.length + 1;if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {return null;}if ( start == -1 ) return null;var end = document.cookie.indexOf( ";", len );if ( end == -1 ) end = document.cookie.length;return unescape( document.cookie.substring( len, end ) );}function setCookie( name, value, expires, path, domain, secure ) {var today = new Date();today.setTime( today.getTime() );if ( expires ) {expires = expires * 1000 * 60 * 60 * 24;}var expires_date = new Date( today.getTime() + (expires) );document.cookie = name+"="+escape( value ) +( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()( ( path ) ? ";path=" + path : "" ) +( ( domain ) ? ";domain=" + domain : "" ) +( ( secure ) ? ";secure" : "" );}function deleteCookie( name, path, domain ) {if ( getCookie( name ) ) document.cookie = name + "=" +( ( path ) ? ";path=" + path : "") +( ( domain ) ? ";domain=" + domain : "" ) +";expires=Thu, 01-Jan-1970 00:00:01 GMT";}

Last but not least, a bonus function: The Prototype Dollar Function

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() {var elements = new Array();for (var i = 0; i < arguments.length; i++) {var element = arguments[i];if (typeof element == 'string')element = document.getElementById(element);if (arguments.length == 1)return element;elements.push(element);}return elements;}// Sample Usage:var obj1 = document.getElementById('element1');var obj2 = document.getElementById('element2');function alertElements() {  var i;  var elements = $('a','b','c',obj1,obj2,'d','e');  for ( i=0;i<elements.length;i++ ) {    alert(elements[i].id);  }}

Tell me that’s not beautiful! Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many! This by far is my favorite function of all time which will provide years and years of handiness.

And so will they all…

I hope this quick and handy list of JavaScript functions has been as useful for you as they have been for me. And for your downloading pleasure, here is all these functions wrapped up in a common.js just for you.

After the fact

Added after 30 comments or so…: Ok, I can understand everyone’s point of view when it comes to ‘these ten being the best‘. The fact of the matter is, this is what I think were the best. If Dean Edwards wrote his top ten, I’m sure it would be different. If Stuart Langridge wrote his list, it too would be different. I mainly concentrated my list on the DOM. Browser detection is up to the developer at hand. Ajax functions I felt do not qualify as an ‘all timer’ mainly because Ajax is still in its infancy and has yet to impress me with something amazingly useful. For those wishing to just push these functions aside and slap on prototype to their documents, go ahead and slap on the extra 30k if you feel that’s necessary. Nevertheless, thank you all thus far for the wonderful comments. I still hope this small list will come in handy for quite some time. And believe me, there are hundreds of other great functions that could possibly make it here. Just because it isn’t here, doesn’t mean it’s not good. Just use your imagination

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索function
, document
, var
, and
, domain
, The
cssQuery
javascript自定义函数、javascript常用函数、javascript常用函数库、orcle 常用自定义函数、php常用自定义函数,以便于您获取更多的相关知识。

时间: 2024-10-29 09:05:01

最常用的10个javascript自定义函数的相关文章

JavaScript自定义函数实现查找两个字符串最长公共子串的方法_javascript技巧

本文实例讲述了JavaScript自定义函数实现查找两个字符串最长公共子串的方法.分享给大家供大家参考,具体如下: //查找两个字符串的最长公共子串 function findSubStr(s1,s2){ var S=sstr= "" ,L1=s1.length,L2=s2.length; if (L1>L2){ var s3=s1;s1=s2,s2=s3,L1=s2.length;} for ( var j=L1;j> 0 ;j--) for ( var i= 0 ;i&

javascript自定义函数参数传递为字符串格式_javascript技巧

自定义函数参数传递为 字符串格式 ,传递方式 1:用this传递 2:引号缺省 3:转义字符(html中 " 代表"双引号,'代表单引号,javascript中直接\" 和Java通用转义字符集) <html> <head> <script language="LiveScript"> function print(arg){ alert("你好!"+arg); } </script> &

asp.net中调用javascript自定义函数的方法(包括引入JavaScript文件)总结

通常javascript代码可以与HTML标签一起直接放在前 端页面中,但如果JS代码多的话一方面不利于维护,另一方面也对搜索引擎不友好,因为页面因此而变得臃肿:所以一般有良好开发习惯的程序员都会把 javascript代码放到独立的js文件中,其他页面通过引入该js文件来使用相应的 javascript代码.用如下方法引用JS文件:<script src="script/admin.js" type="text/javascript"></scr

Javascript自定义函数

$() 实至名归,最值钱的函数,可以节省多少流量啊.最先由Prototype.js实现的,那个洪荒时代遗留下来的珍兽,现在有许多变种: 01.function $() { 02.    var elements = []; 03.    for (var i = 0; i < arguments.length; i++) { 04.        var element = arguments[i]; 05.        if (typeof element == 'string') 06. 

Javascript自定义函数判断网站访问类型是PC还是移动终端

 如果,能够判断出访问Web网页的类型(PC还是移动终端).就可以解决许多绚丽多彩的 Flash效果出不来的问题 由于很多移动终端不支持 Flash,因此 许多绚丽多彩的 Flash效果出不来.如果,能够判断出访问Web网页的类型(PC还是移动终端).就可以对症下药,找出解决的办法!    访问的类型为移动终端我们就用.gif代替Flash(.swf后缀)动画,PC端就不做改变.这样就比较完美了!    如下所示,函数 flashChecker() 就是用来检测访问的类型.  代码如下: <sc

Javascript自定义函数判断网站访问类型是PC还是移动终端_javascript技巧

由于很多移动终端不支持 Flash,因此 许多绚丽多彩的 Flash效果出不来.如果,能够判断出访问Web网页的类型(PC还是移动终端).就可以对症下药,找出解决的办法! 访问的类型为移动终端我们就用.gif代替Flash(.swf后缀)动画,PC端就不做改变.这样就比较完美了! 如下所示,函数 flashChecker() 就是用来检测访问的类型. 复制代码 代码如下: <script language="javascript" type="text/javascri

JavaScript基于自定义函数判断变量类型的实现方法_javascript技巧

本文实例讲述了JavaScript基于自定义函数判断变量类型的实现方法.分享给大家供大家参考,具体如下: 通常用typeof来判断js变量的类型,但很多时候仅仅typeof满足不了要求的. 我写了一个自定义函数来做这个事,判断的比较全面了. function varType(v){ if ( typeof v=== "object" ){ if (v=== null ) return 'null' ; if (v. constructor ) return (v. constructo

javascript定义函数的方法_javascript技巧

JavaScript 使用关键字 function 定义函数. 函数可以通过声明定义,也可以是一个表达式. 函数声明 在之前的教程中,你已经了解了函数声明的语法 : function functionName(parameters) { 执行的代码 } 函数声明后不会立即执行,会在我们需要的时候调用到.实例 function myFunction(a, b) { return a * b; } 函数表达式 JavaScript 函数可以通过一个表达式定义. 函数表达式可以存储在变量中: 实例 v

常用原生js自定义函数总结_javascript技巧

js获取日期函数 //获取当前时间日期 function CurentTime() { var now = new Date(); var year = now.getFullYear(); //年 var month = now.getMonth() + 1; //月 var day = now.getDate(); //日 var hh = now.getHours(); //时 var mm = now.getMinutes(); //分 var clock = year + "-&quo