zoukankan      html  css  js  c++  java
  • [转]JavaScript为事件处理器传递参数

    方法一:
    var newopen = function(id,level)
    {
      return function()
      {
        opentree(id,level);//该函数为外部定义的一个执行函数;
      }
    }
    x.attachEvent("onclick",newopen(id,parseInt(level)+1));
    y.attachEvent("onclick",newopen(id,parseInt(level)+2));

    think8848的简化代码:
    if ( x.addEventListener)    //如果浏览器为Firefox
    {
        x.addEventListener("click",function()
                                                {        
                                                    opentree(id,level);   //opentree为外部定义的一个执行函数,id,level为实参;
                                                });
    }
    else    //浏览器为IE
    {
        x.attachEvent("onclick",function()
                                            {
                                                opentree(id,level); 
                                            });
    }

    方法二:
    <html>
    <head>
     <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
     <title></title>
    </head>
    <body>
     <a href="#" id="mylink">这是连接</a>

     <script type="text/javascript">
    function AttachEvent(type, target, handler, owner)
    {
            var eventHandler = handler;
        if(owner)
        {
        debugger;
                // 在这里重新定义一个处理函数
                eventHander = function(e)
                {
                       handler.call(owner, e);
                }
        }
      
        if(window.document.all)
                target.attachEvent("on" + type, eventHander );
        else
                target.addEventListener(type, eventHander, false);
    }

    function MyLink_Click(e)
    {
            alert(this.tagName);
            var target = e.srcElement || e.target;
            alert(target.href);
    }

    function test()
    {
     var mylink = window.document.getElementById("mylink");
     AttachEvent("click", mylink, MyLink_Click, mylink);

    }
     </script>

     <input type="button" value="AttachEvent" onclick="test()" />
    </body>
    </html>
     

  • 相关阅读:
    New Concept English three (33)
    New Concept English three (32)
    New Concept English three (31)
    2017.11.03 正确查找datasheet+ 英语邮件+英语会议
    New Concept English three (30)
    PyQt(Python+Qt)学习随笔:Qt Designer中窗口对象的windowFilePath属性
    PyQt(Python+Qt)学习随笔:Qt Designer中部件的locale属性
    PyQt(Python+Qt)学习随笔:Qt Designer中部件的autoFillBackground属性
    PyQt(Python+Qt)学习随笔:Qt Designer中部件的样式表styleSheet属性
    PyQt(Python+Qt)学习随笔:Qt Designer中部件的layoutDirection属性
  • 原文地址:https://www.cnblogs.com/think8848/p/1138128.html
Copyright © 2011-2022 走看看