javascript多投事件的处理 (转)
出处 http://blog.csdn.net/dead_of_winter/article/details/1646367
尽管ecma标准指定了addEventListener这样的方法来实现事件多投机制,但是ie ns等浏览器却各行其道,这里利用语言本身的特性来实现事件多投,只要支持简单事件模型,就可以使用。同时FunctionArray也是一个独特的结 构,javascript有趣的特性的体现。
<img id=img1 style="height:100;width:100;"></img>
<br><button onclick="img1.onclick.AddFunction(f1)">添加f1</button><button onclick="img1.onclick.AddFunction(f2)">添加f2</button><button onclick="img1.onclick.AddFunction(f3)">添加f3</button>
<br><button onclick="img1.onclick.RemoveFunction(f1)">移除f1</button><button onclick="img1.onclick.RemoveFunction(f2)">移除f2</button><button onclick="img1.onclick.RemoveFunction(f3)">移除f3</button>
<div id=output></div>
<SCRIPT LANGUAGE="JavaScript">
function FunctionArray()
{
var functions=new Array();
var FA=function (){
for(var i=0;i<functions.length;i++){
if(functions[i] instanceof Function)functions[i].apply(this,arguments);
}
}
FA.AddFunction=function(newFunction){
if(newFunction instanceof Function)
{
for(var i=0;i<functions.length;i++){
if(functions[i]==newFunction)return;
}
functions.push(newFunction);
}
}
FA.RemoveFunction=function(theFunction){
for(var i=0;i<functions.length;i++){
if(functions[i]==theFunction)functions.splice(i,1);
}
}
return FA;
}
img1.onclick=FunctionArray();
function f1()
{
output.innerHTML+="f1 runs!!<br>";
}
function f2()
{
output.innerHTML+="f2 runs!!<br>";
}
function f3()
{
output.innerHTML+="f3 runs!!<br>";
}
</SCRIPT>
<br><button onclick="img1.onclick.AddFunction(f1)">添加f1</button><button onclick="img1.onclick.AddFunction(f2)">添加f2</button><button onclick="img1.onclick.AddFunction(f3)">添加f3</button>
<br><button onclick="img1.onclick.RemoveFunction(f1)">移除f1</button><button onclick="img1.onclick.RemoveFunction(f2)">移除f2</button><button onclick="img1.onclick.RemoveFunction(f3)">移除f3</button>
<div id=output></div>
<SCRIPT LANGUAGE="JavaScript">
function FunctionArray()
{
var functions=new Array();
var FA=function (){
for(var i=0;i<functions.length;i++){
if(functions[i] instanceof Function)functions[i].apply(this,arguments);
}
}
FA.AddFunction=function(newFunction){
if(newFunction instanceof Function)
{
for(var i=0;i<functions.length;i++){
if(functions[i]==newFunction)return;
}
functions.push(newFunction);
}
}
FA.RemoveFunction=function(theFunction){
for(var i=0;i<functions.length;i++){
if(functions[i]==theFunction)functions.splice(i,1);
}
}
return FA;
}
img1.onclick=FunctionArray();
function f1()
{
output.innerHTML+="f1 runs!!<br>";
}
function f2()
{
output.innerHTML+="f2 runs!!<br>";
}
function f3()
{
output.innerHTML+="f3 runs!!<br>";
}
</SCRIPT>