• 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.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>

  • 相关阅读:
    柳下品茗
    游百花诗意亭有感
    爱情如酒
    笑傲IT文坛
    面对诱惑,你会屈从吗?
    拓展人脉的三十六计
    世界经理人推荐:拓展人脉的两大法宝
    我还能做什么
    诗缘
    有谁陪我风雨同舟
  • 原文地址:https://www.cnblogs.com/catprayer/p/1680890.html
Copyright © 2020-2023  润新知