2017-03-05 52 views
2

我有下面的代码触发上的keydown如何用jQuery触发回空间?

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

这清除了输入框的各种活动。但是由于按下了回车键,光标会移到第二行。输入键被释放后,我希望光标回到初始位置;关键了。

有帮助吗?

回答

1

只需添加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>

+0

e.preventDefault()简单地解决了这个问题,谢谢。 – Neo

0
<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script 
    src="https://code.jquery.com/jquery-3.1.1.min.js" 
    integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" 
    crossorigin="anonymous"></script> 
</head> 
<body> 
    <form method="POST" id="userform"> 
     <input type="text" name="firstname" id="firstname"> 
     <input type="text" name="lastname" id="lastname"> 
    </form> 

    <script type="text/javascript"> 
    $("#userform").submit(function(e){ 
     return false;  
    }); 

    $("#userform input").keydown(function(e) { 
     if(e.which == 13) { 
      userInput = $(this).val(); 
      $(this).val(userInput.substring(0,0)); 
      $("#userform input#firstname").focus(); 
     }  
    });  
</script> 
</body> 
</html> 

你可以使用.focus()侧重于具体的输入框