如何在 <input> 中按回车键执行功能?场地? [英] How can I execute a function on pressing the enter key in an <input> field?
本文介绍了如何在 <input> 中按回车键执行功能?场地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入,我只想为它添加一个事件侦听器,以便在我按下 Enter 键时激活一个函数,当输入聚焦时.我如何用纯 JS 做到这一点?
I have an input and I'd simply like to add an event listener for it to activate a function when I press enter, when the input is focused. How do I do this with pure JS?
现在我有:
HTML:
Enter your wage:<input type="text" id="wage" value ="" size=20>
<button id="sub">Submit</button>
JavaScript:
JavaScript:
var wage = document.getElementById("wage");
wage.addEventListener("change", validate);
var btn = document.getElementById("sub");
btn.addEventListener("click", validate);
所以基本上当我单击或更改文本时 validate()
函数会激活,但我想通过按 Enter 来调用它.
So basically the function validate()
activates when I click OR change the text, but I want to call it by pressing enter.
推荐答案
你可以使用这个:
var wage = document.getElementById("wage");
wage.addEventListener("keydown", function (e) {
if (e.code === "Enter") { //checks whether the pressed key is "Enter"
validate(e);
}
});
function validate(e) {
var text = e.target.value;
//validation of the input...
}
这篇关于如何在 <input> 中按回车键执行功能?场地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文