您的位置:首页 > 其它

事件封装(多个函数绑定一个事件,预计这样解释不正确)

2014-08-14 19:13 302 查看
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<!--<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />-->

<title></title>

<style type="text/css">

.red{width:100px;height:100px;background:red;}

.blue{width:100px;height:100px;background:blue;}

</style>

<script type="text/javascript">

/*window.onload=function(){

alert("Lee");

}

if(typeof window.onload=="function"){

var saved=null;

saved=window.onload;

}

window.onload=function(){

if(saved){

saved();

}

alert("Mr.Lee");

}*/

//传统绑定机制

/* window.onload=function(){

var box=document.getElementById("box");

box.onclick=function() {

alert("Lee");

toRed().call(this);

}

}

function toRed(){

// alert(this)

this.className="red";

this.onclick=toBlue;

}

function toBlue(){

this.className="blue";

this.onclick=toRed;

}

*/

/* window["onload"]=function(){

alert("Lee");

}*/

/* function addEvent(obj,type,fn) {

var saved = null;

if (typeof obj['on' + type] == "function") {

saved = obj['on' + type];//保存上一个事件

}

//运行事件

obj['on' + type] = function () {

if(saved)saved();//先运行上一个事件

fn();

}

}

addEvent(window,"load",function(){

alert("Lee");

})

addEvent(window,"load",function(){

alert("Leesss");

})*/

*****************风格线*********这里才是本章高潮处*******************************************************************

//当不断点击的时候,浏览器就会卡死,而且报错:too muchrecursion,太多的递归

//由于积累了太多保存的事件

//解决方式,就是用完事件就马上清除

//移除事件

function removeEvent(obj,type){

if(obj["on"+type]) obj["on"+type]=null;

}

//加入事件

function addEvent(obj,type,fn) {

var saved = null;

if (typeof obj['on' + type] == "function") {

saved = obj['on' + type];//保存上一个事件

}

//运行事件

obj['on' + type] = function () {

if(saved)saved.call(this);//先运行上一个事件

fn.call(this);//这两个地方要加个call呢 不然一会this就指向window了

}

}

addEvent(window,'load',function(){

var box=document.getElementById("box");

addEvent(box,'click',toRed); //this 没有传递过去

})

function toRed(){

this.className="red";

removeEvent(this,'click');//移除事件函数

addEvent(this,'click',toBlue);//加入事件函数

}

function toBlue(){

this.className="blue";

removeEvent(this,'click');//移除事件函数

addEvent(this,'click',toRed);//加入事件函数

}

</script>

</head>

<body>

<div id="box" class="blue">測算点</div>

</body>

</html>



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐