javascript - 如何使用 jQuery 触发退格?

标签 javascript jquery onkeypress

我有下面的代码,可以在按键时触发各种事件

    $('#input-div').keydown(function(e) {
if(e.which == 13) {
    userInput = $(this).val();
    $(this).val(userInput.substring(0,0));

这会清除输入框。但是由于按下回车键,光标转到第二行。我希望在释放回车键后光标回到初始位置;上键。

有什么帮助吗?

最佳答案

只需添加e.preventDefault():

$('#input-div').keydown(function(e) {
  if(e.which == 13) {
    userInput = $(this).val();
    $(this).val(userInput.substring(0,0))
    e.preventDefault()
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input-div"></textarea>

关于javascript - 如何使用 jQuery 触发退格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42605345/

相关文章:

Javascript 函数调用,如 somefunction ("Hi") ("Hello") ("How")

javascript - 如何与 RequireJS 共享全局变量/对象

javascript - 如何在事件发生后重写 jQuery 函数?

javascript - 如何设置onkeypress或onkeydown仅点击一次?

javascript - 在 watch 中测试 Angular 的 $viewContentLoaded

javascript - 如何按包含 Travis CI 徽章状态图像的列对 HTML 表进行排序?

javascript - 无法使用 jQuery 获取 html 表中的同级值

jquery - jQuery BBQ-Plugin 是否仍可与 JQuery 1.7x 一起使用?

javascript - Internet Explorer 中的 onkeypress 调用网页上与按键相关的所有函数

在 iOS 中执行 onkeyup 事件时,Javascript focus() 不起作用