javascript 将按下退格键事件传递给小程序并停止其传播

db2dz4w8  于 2023-01-01  发布在  Java
关注(0)|答案(4)|浏览(112)

我在网页上有一个Java小程序,允许编辑文本。当用户试图修改文本,按退格键,浏览器前进到上一页。如果过滤器退格键按如下:

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

那么退格键不会传播到applet,因此不会修改文本。问题是如何将事件传递到applet并停止进一步传播?

cunj1qz1

cunj1qz11#

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

fsi0uk1n

fsi0uk1n2#

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);
}
ttvkxqim

ttvkxqim3#

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

bihw5rsg4#

// 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);
}

相关问题