十个常用的javascript函数
UPDATE:
For anyone who lands on this article months after the fact
, there is now a
podcast entry
about this article reviewing each and every function.
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
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 ;)
相关推荐
js QQ空间点击Top效果 javascript点击图片 返回页面顶部
在"javascript增删改查,数据存储在top窗口"这个主题中,我们将深入探讨如何利用JavaScript来实现对数据的增删改查操作,并且如何在顶级窗口(top)中进行数据存储。 一、JavaScript数据操作基础 1. 增加(Add):在...
JavaScript植物大战僵尸是一款基于Web的互动游戏,利用JavaScript编程语言实现了原版《植物大战僵尸》的部分核心玩法。在这个项目中,开发者用JavaScript构建了一个小型的游戏环境,玩家可以在浏览器上体验到类似的...
10. 网页将不能被另存为 使用 `<noscript> <* src="/*.html">;*> </noscript>` 可以防止网页被另存为。 11. 查看网页源代码 使用 `查看网页源代码" onclick="window.location = "view-source:"+ ...
tank1.style.top += 10 + 'px'; } } ``` 至于发射炮弹,可以在`keydown`事件中检测空格键是否被按下。如果按下,创建一个新的炮弹元素并设置其初始位置和速度,然后使用定时器每隔一段时间更新其位置,直到炮弹...
### JavaScript 弹出窗口知识点详解 #### 一、基本概念 **JavaScript** 是一种轻量级的编程语言,常用于网页交互式的实现。通过 **JavaScript** 可以控制浏览器的行为,比如创建弹出窗口。 #### 二、创建弹出窗口...
10. 文本框光标定位:`<script language="javascript">function cc(){...}</script><input type=text name=text1 value="123" onfocus="cc()">` 当文本框获得焦点时,自动将光标移动到文本末尾。 11. 获取上一页...
Learn about modern web architectures and build real-world apps on top of them Who This Book Is For This course is for experienced developers familiar with other object-oriented languages who wants to...
标题“javascript IE窗口居中”涉及的是在Internet Explorer(IE)浏览器中,使用JavaScript实现弹出窗口自动居中的技术。JavaScript是一种广泛应用于网页和网络应用的脚本语言,它允许开发者在用户与网页交互时动态...
这通常涉及到改变元素的`style.left`或`style.top`属性,以创建一种循环滚动的效果。可以设置定时器使文字不断移动,当文字到达边缘时,再回到初始位置。 4. **动态时钟**:JavaScript可以实时更新页面上的时间,...
JavaScript小贴士要点 在网页开发中,JavaScript是一种不可或缺的语言,它赋予了页面动态交互的能力。本篇将探讨几个实用的JavaScript小贴士,帮助开发者更高效地利用JS来提升用户体验,尤其是创建类似小贴士的功能...
本主题将探讨如何使用jQuery和纯JavaScript实现客户端验证,包括图片轮换、Tab切换、图片上下滚动以及表单验证。 首先,jQuery是一个轻量级的JavaScript库,它使得JavaScript的使用更加简洁和高效。在图片轮换功能...
.top样式设置了标题的字体、颜色等样式。 JavaScript技术是用于控制网页行为的语言,主要用于实现网页的交互效果。JavaScript技术可以用于实现网页的动态效果,例如弹出消息框、日期时间显示、鼠标闪烁效果等。 在...
JavaScript是一种广泛应用于网页和网络应用的脚本语言,它在浏览器环境中执行,为用户提供动态交互。在本主题“JavaScript实现自由落体”中,我们将深入探讨如何利用JavaScript模拟物理学中的自由落体运动,创建出一...
7. 样式和布局:代码使用了 CSS 样式和布局,例如 `style` 属性和 `left`、`top` 属性,用于控制游戏对象的显示和布局。 8. 游戏事件:代码实现了游戏事件,例如敌方对象的移动和检测我自己对象的附近。 9. 游戏...
在JavaScript编程领域,实现支持放大显示效果的TOP排行源码是一项常见的需求,尤其在前端开发中,这样的功能常用于数据可视化或用户交互增强。本文将深入探讨如何利用JavaScript实现这一功能,并结合ECMAScript(ES...
10. ARIA(无障碍富互联网应用)支持:JavaScript可以帮助改进无障碍性,如设置aria-label、aria-live属性,让屏幕阅读器更好地理解网页内容。 最后,学习JavaScript特效不仅仅是代码的实现,还需要理解浏览器兼容...
2. **动画原理**:JavaScript可以通过修改元素的CSS属性(如`left`, `top`, `opacity`等)来实现平滑的动画效果。使用`requestAnimationFrame`函数可以确保动画在浏览器的下一帧渲染时执行,提供流畅的视觉体验。 3...
10. `查看网页源代码 onclick="window.location = `view-source:`+ http://www.51js.com/`;">`:这个按钮会跳转到浏览器的源码查看器,并显示指定网页的源代码。 11. 删除时确认:`<a href=`javascript:if(confirm...
top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 9999; } #modal-content { position: fixed; width: 400px; /* 示例宽度 */ height: 300px; /* 示例高度 *...