JavaScript通过attachEvent和detachEvent方法处理带参数的函数

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2<html xmlns="http://www.w3.org/1999/xhtml">
 3<head>
 4<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5<title>无标题文档</title>
 6<script language="javascript">
 7
 8    var theP;  //P标签对象
 9   
10    var show=function(msg){    //直接定义 function show(msg) 效果是一样的
11        return function(){   
12            alert(msg+" from show()");
13
14            if(window.addEventListener){  //FF etc.
15                 theP.removeEventListener("click", theP.show11, false);
16            }
17            else{ //IE
18                 theP.detachEvent("onclick", theP.show11);
19            }
20        }
21    }
22
23    var show2=function(msg){    //直接定义 function show2(msg) 效果是一样的
24        return function(){   
25            alert(msg+" from show2()");
26        }
27    }
28   
29    function showDef(){
30        alert("showDef()");           
31       
32         if(window.addEventListener){  //FF etc.
33              theP.removeEventListener("click", showDef, false);
34         }
35         else{ //IE
36              theP.detachEvent("onclick", showDef);
37         }
38    }
39   
40    window.οnlοad=function(){
41        theP=document.getElementById("pid");
42       
43        theP.show11=show("可以detach的带参数方法");
44       
45        if(window.addEventListener) // not IE
46        {
47            //for FF.etc
48            theP.addEventListener("click", theP.show11, false);
49            theP.addEventListener("click", showDef, false);
50        }
51        else
52        {
53            //for IE           
54            theP.attachEvent("onclick", theP.show11);
55            theP.attachEvent("onclick", show2('不能detach的带参数方法'));//区别于上一个,这里不能detach
56           
57            theP.attachEvent("onclick", showDef);  //无参数的方法直接写
58        }       
59    }
60</script>
61
62</head>
63
64<body >
65<div >
66    <p id="pid">Click Me</p>
67</div>
68</body>
69</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值