How to register [removed] event

后端 未结 3 1071
南方客
南方客 2020-12-05 04:09

I want to register keypress events for a document using javascript.

I have used:

document.attachEvent(\"onkeydown\", my_onkeydown_handler);


        
相关标签:
3条回答
  • 2020-12-05 04:49

    You are probably looking for:

    document.body.addEventListener('keydown', function (e) {
        alert('hello world');
    });​​​​​​​
    

    But it is almost certainly going to be worth your time to use an existing library to abstract over the problems of the many browsers out there.

    0 讨论(0)
  • 2020-12-05 04:57

    Please go through following links for detailed description.

    https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener

    http://www.reloco.com.ar/mozilla/compat.html

    In short, write handler as

    function myFunction(e)
    {
        ///For IE
        if(!e)
            e=window.event;
    
        // use e as event in rest of code.
    }
    
    0 讨论(0)
  • 2020-12-05 05:02

    You are looking for:

    EDIT:

    Javascript:

    document.addEventListener("keydown", keyDownTextField, false);
    
    function keyDownTextField(e) {
    var keyCode = e.keyCode;
      if(keyCode==13) {
      alert("You hit the enter key.");
      } else {
      alert("Oh no you didn't.");
      }
    }
    

    DEMO: JSFIDDLE

    0 讨论(0)
提交回复
热议问题