我想把窗口中按下的按键显示到文本框中,但window事件的触发后,所调用的方法,是不能带参数的。
记得有一次在csdn中看到过,但当时只是无意中看到的,当时没有用,所以也没有记下来。现在再想找就找不到了。
而且现在csdn很奇怪,写标题的时候,不像以前那样会出现近似的标题。例如下面的代码:<html>
<body>
<input id=a><script>
function test(b){
a.value=b;
}window.onkeypress=test(event.keyCode);
</script>
</body>
</html>那么,我应该怎样改写代码呢?

解决方案 »

  1.   

    <html>
    <body>
    <input id=a>
    <script>
    document.onkeypress=function(event){
    var e = event||window.event;
    var keyCode = e.which||e.keyCode;
    document.getElementById("a").value=keyCode;
    }
    </script>
    </body>
    </html>
      

  2.   

    window.onkeypress=function(e){
    //为了兼容兼容建议写成e=window.event ||e;
    test(event.keyCode);
    }
      

  3.   

    我的问题的window.onkeypress=xxxx()只是举个例子,如果是其他如onXXXXX什么的,怎样才能给=右边的方法用上参数呢?
    是不是全部都用window.onxxxxx=function xxxx(a){}都可以解决我的需求呢?谢谢。
      

  4.   

    只要是"事件"就可以用 event对象
      

  5.   

    window.onkeypress=test(event);
    function test(obj){
       alert(e.keyCode);//键值
    }
      

  6.   

    <html>
    <body>
    <input type="button" id="b"><script>
    function test(b){
    alert(b);
    }var x = "123";document.getElementById("b").onclick=(function(v){return function(){test(v);}})(x);
    </script></body>
    </html>
    可能写得难看了点,但是是这个意思,呵呵