JavaScript:在调用函数的文本输入上按Enter键

Abd*_*zic 1 html javascript css

http://codepen.io/abdulahhamzic/pen/YqMQwB

我怎么做到这样当我按下输入文本输入时,它调用一个函数?我试过用这个:

<input type="text" onkeypress="clickPress()">   
Run Code Online (Sandbox Code Playgroud)

但问题是我只想按Enter键调用该功能,而不是按任意键.我如何实现这一目标?

Ala*_*out 6

您要做的是检查事件的键是否为回车键:

在你的html中,添加event参数

<input type="text" onkeypress="clickPress(event)">
Run Code Online (Sandbox Code Playgroud)

在处理程序中,添加一个事件参数

function clickPress(event) {
    if (event.keyCode == 13) {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)


BDa*_*awg 6

使用表单代替(提交事件仅运行一次,而不是每次按键时运行):

// Attach the event handler to the form element
document.querySelector('.js-form')?.addEventListener('submit', e => {
  e.preventDefault();
  alert(e.currentTarget.myText.value);
});
Run Code Online (Sandbox Code Playgroud)
<form class="js-form">
  <input type="text" name="myText">
</form>
Run Code Online (Sandbox Code Playgroud)