JavaScript通過attachEvent和detachEvent方法處理帶參數的函數

來源:互聯網
上載者:User

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>

出處:http://www.cnblogs.com/Freeway/archive/2009/06/03/1495561.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.