问题
Inside a function I have an event handler. So far so good. But in that event handler I want to capture Enter pressed and replace that for a HTML.
I've done it like this:
CrossBrowserEventHandler(Editor, 'keyup', function(Event) { myFunctionRef(idname, Event) });
var myFunctionRef = function myFunction(idname, Event)
{
var keyCode;
if (!Event && window.event) {
Event = window.event;
}
if (Event) {
keyCode = (window.Event) ? Event.which : Event.keyCode;
if (keyCode == 13) {
Event.target.ownerDocument.execCommand("inserthtml",false,'<br />');
Event.returnValue = false;
}
}
PushText(idname); /* pushes the input from a rich text iframe to a textarea */
}
The cross browser event handler function looks like this:
function CrossBrowserEventHandler(target,eventName,handlerName)
{
if (target.addEventListener) {
target.addEventListener(eventName, handlerName, false);
}
else if (target.attachEvent) {
target.attachEvent("on" + eventName, handlerName);
}
else {
target["on" + eventName] = handlerName;
}
}
In the first part I capture the keycode 13 (return) and replace it via an execCommand to a HTML line break. It does that, but twice. It doesn't cancel/remove the actual return-pressed event.
Any ideas (besides the standard advice to use a JS framework, which I can't for numerous reasons, one of them being the process of actually learning something)?
回答1:
Shouldn't you be capturing key-code 10 instead of 13? 10 stands for newline character while 13 stands for carriage return.
EDIT: You may be getting the event twice either a) you might have registered it twice or b) event might be bubbling up. For b, I will suggest that you cancel bubbling such as
...
if (keyCode == 13) {
Event.target.ownerDocument.execCommand("inserthtml",false,'<br />');
Event.returnValue = false;
Event.cancelBubble = false;
}
...
Yet, another suggestion is to return false from the event handler function. For example,
...
Event.returnValue = false;
Event.cancelBubble = false;
return false;
}
...
And
CrossBrowserEventHandler(Editor, 'keyup', function(Event) { return myFunctionRef(idname, Event) });
来源:https://stackoverflow.com/questions/3748985/cross-browser-event-handler-must-capture-enter