JavaScript add an event listener any time and remove the event listener any time
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 dialog is visible.
When I close the modal dialog I want to stop the keystroke processing.
consider that I click a button and function
sam()is called.function sam() { document.onkeypress = function(e) { processKeystroke(e); } }So now a function is attached to the
keypressevent. Whenever a key is pressed the functionprocesskeystrokewill be called. The functionsamis called only after I display the modal dialog box.Now I am 开发者_如何转开发closing the modal dialog and with that I don't want
function(e) { processKes...}to be called.What should I do to remove the attached event listener from
document.onkeypress.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.
So when I call function
samI want a function to be attached with thekeypressevent and if I call another function form exampleclosedialog()I want thatkeypresslistening 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.
加载中,请稍侯......
精彩评论