【问题标题】:make form visible on keydown event then focus and clear input field使表单在 keydown 事件上可见,然后聚焦并清除输入字段
【发布时间】:2015-07-09 12:44:33
【问题描述】:

我有一个表格,其中单元格接受键盘事件。我也有一个最初隐藏的表格。我想要一个键事件来显示表单并关注输入字段,但是当我这样做时,触发事件的键值出现在输入字段中 - 我怎么能不显示这个字符? (例如,按“x”,表单会在文本字段中显示“x” - 我希望该字段为空白)。

CSS

table.thistbl td {
  border: 2px solid black;
  width: 20px;
  height: 20px;
  padding: 5px;
}

#formid {
  display: none;
  position: absolute;
  width: 300px;
  height: 40px;
  left: 20px;
  top: 60px;
  background-color: #CCC;
}

JavaScript / jQuery:

$(function() {

  $('#tablediv').on('keydown', 'td', function(e) {
      $('#formid').show();
      $('#inputid').focus();
  });

});

HTML:

<div id="tablediv">
<table class="thistbl">
  <tr>
    <td tabindex="0"></td>
    <td tabindex="0"></td>
    <td tabindex="0"></td>
  </tr>
</table>
</div>

<form id="formid">
  <input type="text" tabindex="1" id="inputid" />
</form>

Fiddle

【问题讨论】:

  • 只是一个想法...:您可以尝试使用 keyup-event 来代替吗?

标签: javascript jquery html forms


【解决方案1】:

尝试keyup 而不是keydown

Fiddle here

【讨论】:

  • Arg - 太简单了!谢谢!
【解决方案2】:

短暂的延迟怎么样?

$('#tablediv').on('keydown', 'td', function(e) {
    setTimeout(funtion(){
        $('#formid').show();
        $('#inputid').focus();
    }, 20);
});

【讨论】:

    【解决方案3】:

    如果您坚持使用keydown,请添加e.preventDefault() 以防止该事件的默认行为。但我认为 KiiroSora09 的答案是切换到keyup 更好。

    $(function() {
    
      $('#tablediv').on('keydown', 'td', function(e) {
          e.preventDefault();
          $('#formid').show();
          $('#inputid').focus();
      });
    
    });
    table.thistbl td {
      border: 2px solid black;
      width: 20px;
      height: 20px;
      padding: 5px;
    }
    
    #formid {
      display: none;
      position: absolute;
      width: 300px;
      height: 40px;
      left: 20px;
      top: 60px;
      background-color: #CCC;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="tablediv">
    <table class="thistbl">
      <tr>
        <td tabindex="0"></td>
        <td tabindex="0"></td>
        <td tabindex="0"></td>
      </tr>
    </table>
    </div>
    
    <form id="formid">
      <input type="text" tabindex="1" id="inputid" />
    </form>

    【讨论】:

    • 这也有效,但在我的应用程序中,我使用 keyup 没有问题,所以我可以坚持下去。谢谢!
    【解决方案4】:

    尝试包括

    $('#inputid').focus().attr('value', '');
    

    你实际上在这里做的是在专注于清空value之后

    如下图

    $(function() {
    
      $('#tablediv').on('keydown', 'td', function(e) {
          $('#formid').show();
          $('#inputid').focus().attr('value', '');
      });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      相关资源
      最近更新 更多