如何在js中按enter键时添加EventListener



我有1个textbar,我想用键盘上的Enter键从用户那里获得值,然后运行一个函数(我的函数名为newNote(。我的代码是这样的,对吧?

function eventListeners(){
document.querySelector("#note").addEventListener("keypress", function (e){
if (e.key === "Enter"){
newNote();
}
})
}

我试着找到正确的答案:

function nameOfYourEventListener(){
document.querySelector("#yourInputID").addEventListener("keydown", function (e){
if (e.code === 'Enter'){
newNote(e); //function that you run for add the content to the list
}});

解决方案


function eventListeners(){
let targetInput = document.querySelector('#inputId');
document.querySelector("#note").addEventListener("keypress", function (e){
if (e.key === "Enter"){

let value = target.value; // do something with the value
newNote();
}
})
}

最新更新