开发者

JavaScript add an event listener any time and remove the event listener any time

开发者 https://www.devze.com 2023-01-14 18:31 出处:网络
In a web page I have a button when clicked it calls a JavaScript function. In that function I show a modal dialog box and I want to process keystrokes only at this time. That is when the modal dialo
  1. In a web page I have a button when clicked it calls a JavaScript function.

  2. In that function I show a modal dialog box and I want to process keystrokes only at this time. That is when the modal dialog is visible.

  3. When I close the modal dialog I want to stop the keystroke processing.

  4. consider that I click a button and function sam() is called.

    function sam()
     {
      document.onkeypress = function(e) { processKeystroke(e); }
     }
    
  5. So now a function is attached to the keypress event. Whenever a key is pressed the function processkeystroke will be called. The function sam is called only after I display the modal dialog box.

  6. Now I am 开发者_如何转开发closing the modal dialog and with that I don't want function(e) { processKes...} to be called.

  7. What should I do to remove the attached event listener from document.onkeypress.

  8. Also I would like to have alternatives for the above approach because that one I assumed of my own and I did not refer any specific documentation, so I am really going through trial and error procedure to use event handlers or listeners.

  9. So when I call function sam I want a function to be attached with the keypress event and if I call another function form example closedialog() I want that keypress listening function to be removed. Because I want to write proper code which should not consume lots of system resources.


Just write the following code to remove the handler.

 document.onkeypress = null;

Since you are talking about attaching you maybe should check jquery which provides real bind (attach) and unbind (detach) for events like keypress.

0

精彩评论

暂无评论...
验证码 换一张
取 消