跨浏览器事件处理程序必须捕获[ENTER] [英] Cross browser event handler must capture [ENTER]
问题描述
在函数中,我有一个事件处理程序.到现在为止还挺好.但是在该事件处理程序中,我想捕获按下的 Enter 并将其替换为HTML.
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.
我这样做是这样的:
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;
}
}
在第一部分中,我捕获了键码13(返回),并通过execCommand将其替换为HTML换行符.它做到了,但是两次.它不会取消/删除实际的按下返回事件.
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.
有什么想法(除了使用JS框架的标准建议之外,出于各种原因,我不能这样做,其中之一是实际学习某些东西的过程)?
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)?
推荐答案
您不是要捕获键码10而不是13吗?10代表换行符,而13代表回车符.
Shouldn't you be capturing key-code 10 instead of 13? 10 stands for newline character while 13 stands for carriage return.
您可能会两次获得该事件,或者a)您可能已经两次注册该事件,或者b)事件可能正在冒泡.对于b,我建议您取消冒泡,例如
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;
}
...
但是,另一个建议是从事件处理程序函数返回false.例如,
Yet, another suggestion is to return false from the event handler function. For example,
...
Event.returnValue = false;
Event.cancelBubble = false;
return false;
}
...
还有
CrossBrowserEventHandler(Editor, 'keyup', function(Event) { return myFunctionRef(idname, Event) });
这篇关于跨浏览器事件处理程序必须捕获[ENTER]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!