有时候,我们需要一个时间触发多个处理函数,这个时候简单的 e.attachEvent似乎已经不能满足我们的要求,今天编写页面,想通过 class定义了一批组件的风格,但又希望它们能够响应鼠标操作而改变风格,却不至于影响事件。
我今天就遇到了这个问题。从互联网上搜索了一下,找到了一个,用了一下,感觉还可以。但是,随着深入,这个看起来完美的例子 问题也就渐渐显现出来。缺陷是,不能响应在 html标签内定义好的事件。例如:
<
input
type
="text"
class
="textbox"
onfocus
="alert('good');"
/>
在使用委托后,这个 alert()就不会被执行了。怎么改好这个问题呢?这个好说。呵呵……。稍微修改了下前人的代码。一切OK。
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=gb2312"
/>
<
title
>
无标题文档
</
title
>

<
style
>
...

.textbox {...}{
background-image: url(images/input.png);
border:1px solid #999999;
line-height:20px;
height:20px;
}

.textbox_focus {...}{
background-image: url(images/input.png);
background-position:0px -100px;
border:1px solid #00CC00;
line-height:20px;
height:20px;
}
</
style
>
</
head
>

<
body
onload
="setStyle()"
>
<
input
type
="text"
class
="textbox"
onfocus
="alert('good');"
/>
<
input
type
="text"
class
="textbox"
/>
</
body
>

<
script
>
...

function delegate(func)...{
this.arr = new Array(); // 回调函数数组
this.nrr = new Array();

this.add = function(n,func)...{
this.arr[this.arr.length] = func;
if(n.substring(0,2)=='on')
this.nrr[this.nrr.length] = n.substring(2);
else
this.nrr[this.nrr.length] = n;
};

this.run = function(e)...{

for(var i=0;i<this.arr.length;i++)...{
var func = this.arr[i];

if(typeof func == "function")...{
if(this.nrr[i]==e.type)
func(); // 遍历所有方法以及调用
}
}
}
}
// 新建一个实现attach event的函数

function mrun_event()...{
this.dEv.run(event);
}

function mAttachEvent(obj,sEvent,func)...{
if(!obj.dEv) obj.dEv = new delegate();

if(null!=eval("obj."+sEvent) && eval("obj."+sEvent+"!=mrun_event"))...{
eval("obj.dEv.add('"+sEvent+"',obj."+sEvent+")");
}
obj.dEv.add(sEvent,func);
eval("obj." + sEvent + " = mrun_event");
}

function setStyle()...{
var ipts=document.getElementsByTagName('input');

for(i=0;i<ipts.length;i++)...{

mAttachEvent(ipts[i],'onfocus',function()...{
e=event.srcElement;

switch(e.className)...{
case 'textbox':
e.className='textbox_focus';break;
}
});

mAttachEvent(ipts[i],'onblur',function()...{
e=event.srcElement;

switch(e.className)...{
case 'textbox_focus':
e.className='textbox';break;
}
});
}
}
</
script
>
</
html
>