简体   繁体   中英

In client-side JavaScript, is it possible to capture an event and fire it at a later stage?

I'm interested in doing something like this:

...
event.preventDefault();
...
el.dispatchEvent(event);

I tried this in Firefox, which threw an NS_ERROR_ILLEGAL_VALUE exception.

Is it possible to capture an event and fire it at a later stage?


For those that are interested, here's my high-level objective. I'm trying to determine when an underscore is typed into a textarea (ie shift + - ). Unfortunately, Firefox reports the keyCode and charCode for this event are 0, the same value given to the tilde ( shift + ` ) keystroke. To disambiguate, my idea is to capture the event, suppress its default behaviour, and "release" it on another textarea. I'd then inspect the value of this (hidden) textarea to determine which key was pressed.

Update: I'm using onkeydown , not onkeypress .

As far as I know, an event already in the queue cannot be "reused" because it cannot be "pulled out" of the queue. It's given to you, then to the next handler in line, and so on, but the native delegate is the same for all of them. So, you have to make a new one. Since you're saying you can't get all the data about the event out, that's a problem.

An easier trick may be to watch the textarea for change, and then delete the underscore when it appears in the text. If you want to maintain the cursor position, you can look here for a solution on how to exactly position the cursor (RonPK's response).

Out of curiosity, according to my test here , Firefox 4 reports the correct charCode and shift state. Is this a specific version/OS issue?

What's wrong with:

String.fromCharCode(event.keyCode);

?

Eg within the event handler:

var character = String.fromCharCode(event.keyCode);
if (character === '_') {
    // Do something.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM