JavaScript通过attachEvent和detachEve...

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.onload=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>
Tags: 

延伸阅读

最新评论

发表评论