【问题标题】:HTML textboxes are not workingHTML 文本框不工作
【发布时间】:2018-05-21 10:55:15
【问题描述】:

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

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

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

【问题讨论】:

  • eventevent.keyCode 中应该是e

标签: javascript jquery html keydown preventdefault


【解决方案1】:

目前您的“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" />

固定版本:

我只是在 if 语句中移动了 preventDefault() 来检测按下的确切键。

$(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"/>

附:我还在您的 if 语句中修复了 e / event 混淆。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        问题:

        您将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"))));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多