HTML 文本框不工作

HTML textboxes are not working

我想在单击 F1 按钮时从当前页面重定向到下一页。页面正确重定向,但当前页面的文本框不工作。

$(document).ready(function () {
    $("body").keydown(function (e) {
        e.preventDefault();
        if (event.keyCode === 112) {
            window.location.href = "../nextpage.aspx";
        }
    });
});

我应该怎么做才能解决这个问题?

更改 if (e.keyCode === 112) 而不是 if (event.keyCode === 112)

目前您的 "preventDefault()" 在 所有 情况下触发,阻止其他键正常工作。如果您检测到该键具体是 F1,您真的只需要这样做:

非工作代码演示:

请注意,无法在文本框中键入任何内容,因为每个键的默认行为都被抑制了。

$(document).ready(function() {
  $("body").keydown(function(e) {
    e.preventDefault();
    if (e.keyCode === 112) {
      window.location.href = "../nextpage.aspx";
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

固定版本:

我只是将 preventDefault() 移动到 if 语句中,它检测到按下的确切键。

$(document).ready(function() {
  $("body").keydown(function(e) {
    if (e.keyCode === 112) {
      e.preventDefault();
      window.location.href = "../nextpage.aspx";
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>

P.S。我还在您的 if 语句中修复了 e / event 混淆。

问题:

您将 event 定义为 e 但将其用作 event

代码:

$(document).ready(function () {
        $("body").keydown(function (e) {
            if (e.keyCode === 112) { // error was here
                e.preventDefault(); // should be inside if statement
                window.location.href = "../nextpage.aspx";
            }
   });
});

更新代码(稍好一点):

$(document).ready( () => $("body").keydown((e) => e.keyCode == 112&&(e.preventDefault(),(window.location.href= "../nextpage.aspx"))));

e.preventDefault(); 正在阻止您页面中的所有按键操作。
只需像这样更改您的代码:

$(document).ready(function () {
    $("body").keydown(function (e) {
        if (e.keyCode === 112) {
            e.preventDefault();
            window.location.href = "../nextpage.aspx";
        }
     });
});