将退格键按下事件传递给applet并停止传播

时间:2009-10-14 09:44:40

标签: javascript javascript-events

我在网页上有一个允许编辑文本的Java小程序。当用户尝试修改文本时,按退格键,浏览器会转到上一页。如果过滤器退格按

var a = function () {
        var event = window.event;
        if (event.keyCode == 8){
            alert('backspace');
            return false;
        }
}
document.onkeydown = a;

然后退格不会传播到applet,因此不会修改文本。 问题是如何将事件传递给applet ant stop进一步传播?

4 个答案:

答案 0 :(得分:1)

现在我找到使用jQuery sendkeys plugin的解决方案。由于在我们的项目中使用jQuery不是一个选项,我会尝试用普通的javascript重写它。

答案 1 :(得分:0)

if (event.keyCode === 8)
{
   var newEvent = document.createEvent('KeyboardEvent');
   newEvent.initKeyEvent(                                                                                      
                 "keypress",        //  in DOMString typeArg,                                                           
                  true,             //  in boolean canBubbleArg,                                                        
                  true,             //  in boolean cancelableArg,                                                       
                  null,             //  in nsIDOMAbstractView viewArg,  Specifies UIEvent.view. This value may be null.     
                  false,            //  in boolean ctrlKeyArg,                                                               
                  false,            //  in boolean altKeyArg,                                                        
                  false,            //  in boolean shiftKeyArg,                                                      
                  false,            //  in boolean metaKeyArg,                                                       
                   8,               //  in unsigned long keyCodeArg,                                                      
                   0);              //  in unsigned long charCodeArg); 
   document.getElementById('myjavaapplet').dispatchEvent(newEvent);
}

答案 2 :(得分:0)

if (event.keyCode === 8)
{
    var newEvent = document.createEvent('UIEvents');
    newEvent.initUIEvent( 'keypress', true, true, window, 1 );
    newEvent.keyCode = 8;
    document.getElementById('myjavaapplet').dispatchEvent(newEvent);
}

答案 3 :(得分:0)

// assumes IE8, but you could write detection code based on if (document.createEventObject)

if (event.keyCode === 8)
{
    var newEvent = document.createEventObject();
    newEvent.keyCode = 8;
    document.getElementById('myjavaapplet').fireEvent('onkeypress',newEvent);
}