سؤال

I am trying to write a web page that can catch onkeyup events.

It uses document.write("..."); to print the keycode each time.

However it only works once, the second time I use it, the window does not update.

Here is the code:

document.onkeyup = function checkKeys(event) {
    var keyCode = event.which || event.keyCode;
    document.write(keyCode);
};

Why does this only catch the event once?

هل كانت مفيدة؟

المحلول 2

document.write(keyCode); is overwriting the page each time with the new keycode, you need to append to the document, preferably a div on the page:

<div id="keyupDiv"></div>

document.getElementById("keyupDiv").innerHTML += keyCode; 

نصائح أخرى

Don't use document.write(). It's wiping the page clean, along with the onkeyup handler. Create an element on the page and update the element's contents.

document.onkeyup = function checkKeys(event) {
    var keyCode = event.which || event.keyCode;
    document.getElementById( 'results' ).innerText = keyCode;
};

HTML:

<div id="results"></div>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top