【问题标题】:Firefox: pass event from anonymous javascript functionFirefox:从匿名 javascript 函数传递事件
【发布时间】:2010-09-24 11:55:23
【问题描述】:

在这段简短的代码中,内联事件起作用——“事件”被传递给 testKeyPress 函数

<textarea id="source"
    onkeydown= "showCursPos(this); 
    var tf=testKeyPress(event);
    document.onkeypress=function(){return tf};
    document.onkeydown=function(){return tf}; " ></textarea>

function testKeyPress(e){
    if (e.ctrlKey==true ){
        if (e.which == null ){kcode=e.keyCode; }  // IE
        else if (e.which > 0){kcode=e.which; }    // gecko
        return testValidity(kcode);   //returns true-false
    }
}

但是,在这个匿名版本中,gecko 中没有传递事件:

<textarea id="source"></textarea>

$("source").onkeydown = function(){ 
    showCursPos(this);  // this function works
    // next event is passed in IE, but not gecko
    var tf=testKeyPress(event); 
    // remaining functions work if value is forced
    document.onkeypress=function(){return tf}; 
    document.onkeydown=function(){return tf}; 
    }

如何传递函数自身的事件?

【问题讨论】:

    标签: anonymous-function event-handling event-passthrough


    【解决方案1】:

    是的,有一个事件对象作为参数。

    你可以通过

    var e=arguments[0] || event; // Firefox via the argument, but IE don't
    

    我不知道它们是否完全相同,但我将&lt;xxx onkeydown="func(event);"&gt; 读作xxx.ononkeydown=function(event){func(event);};

    参考event @ Mozilla.org

    【讨论】:

      【解决方案2】:

      工作就像一个魅力。对我的原始代码的这种修改成功地将事件从匿名函数传递到我的四个浏览器中的命名函数:IE6、FF2、NS7.2、OP9.22

      $("source").onkeydown = function(){ 
          var e=arguments[0] || event; 
          showCursPos(this);  
          var tf=testKeyPress(e); 
          document.onkeypress=function(){return tf}; 
          document.onkeydown=function(){return tf}; 
      }
      

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多