现代的事件处理函数,其递归的原理是什么?
我写了一个事件切换器,原始的一个div颜色为红色,点击后变成蓝色,再点击又变成红色,就这样切换。代码如下:
HTML代码:
<head>
<style type="text/css">
#box{
width:100px;
height:100px;
}
.red{
background-color:red;
}
.blue{
background-color:blue;
}
</style>
</head>
<body>
<div id="box" class="red">颜色切换器</div>
</body>
JS代码:
//事件添加函数
function addEvent(obj, type, fn){
var saved = null;
if(obj.type){
saved = obj.type;
}
obj.type = function(){
if(saved) saved();
fn.call(this);
};
}
//事件删除函数
removeEvent(obj, type){
if(obj.type) obj.type = null;
}
//颜色切换函数
function toBlue(){
this.className = 'blue';
removeEvent(this, 'onclick');
addEvent(this, 'onclick', toRed);
}
function toRed(){
this.className = 'red';
removeEvent(this, 'onclick');
addEvent(this, 'onclick', toBlue);
}
//开始执行
addEvent(window, 'onload', function(){
var box = document.getElementById('box');
addEvent(box, 'onclick', toBlue);
});
当开始执行时,首先点击了div,颜色变蓝,再点击就变红,切换时的运行机理是什么?为何点击后还能继续成功点击?