输入类型文本和onKeyDown在IE下不起作用

Krz*_*ter 0 html javascript dhtml javascript-events

我正在编写一个WWW应用程序,它必须在IE下运行.我有在FF下运行的代码的问题,但我不能让它在IE下运行.

// JS代码

function test()
{
    if (window.event.keyCode == 13)
        window.location.assign("myPage.php");
}
Run Code Online (Sandbox Code Playgroud)

我在window.location和location.href周围尝试了一些类似的方法,也是document.location.我已经读过IE有问题,所以我要求一个解决方案.

目标是,在输入一些文本后重新加载该页面<input type='text' name='item_code' onKeyDown='test()'>,然后单击Enter.因此结果类似于在文本输入下方按提交类型按钮.

在IE中,它重新加载相同的页面,没有任何反应.在FF它正确工作.

更新1:

由bobince给出的尝试解决方案.

<input type='text' name='item_code'>

<script type='text/javascript' >

document.getElementsByName('item_code')[0].onkeydown = function(event)
{
    if (event == undefined) { event = window.event; }
    if (event.keyCode == 13) { window.location = 'myPage.php'; }

    alert('1');
}

</script>";
Run Code Online (Sandbox Code Playgroud)

问题是,如果有alert('1');行,页面显示警报和重定向,如果没有alert('1');行,页面只是重新加载到自身.我不知道这里有什么问题?

更新2:

我正在粘贴最终适合我的东西.

<form action='mainPage.php' method='POST'>
    <input type='text' name='item_code'>
</form>

<script type='text/javascript' >
    document.getElementsByName('item_code')[0].onkeydown= function(event)
    {
        if (event == undefined)
        {    
            event = window.event;
        }

        if (event.keyCode == 13)
        {
            var js_item_code = document.getElementsByName('item_code')[0].value;
            window.location = 'myPage.php?item_code='+js_item_code;
            return false;
        }
    };
</script>
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 5

这很奇怪,因为你的使用window.event应该确保你的功能只能在IE中运行.当我尝试你的代码时,这肯定会发生在我身上.我怀疑还有更多你没有向我们展示.

使用内联事件处理程序属性以跨浏览器方式处理事件的常用方法是:

<input type="text" name="item_code" onkeydown="test(event)">

function test(event) {
    if (event.keyCode===13)
        window.location.href= 'myPage.php';
}
Run Code Online (Sandbox Code Playgroud)

这是因为event在属性中引用window.eventIE中的全局,其中在每个其他浏览器中它引用一个名为event传入事件处理程序属性函数的本地参数.

但是,通常认为避免事件处理程序属性并从JavaScript本身分配处理程序会更好.在这种情况下,您需要检查以查看要使用的内容:

<input type="text" name="item_code">

// in a script block after the input, or in document-ready code
//
document.getElementsByName('item_code')[0].onkeydown= function(event) {
    if (event===undefined) event= window.event; // fix IE
    if (event.keyCode===13)
        window.location.href= 'myPage.php';
};
Run Code Online (Sandbox Code Playgroud)

一般情况下,我只会尝试捕获Enter keypresses以重现/更改默认表单提交行为作为最后的手段; 如果你能让表单提交到你想要的地方,那就更好了.