简体   繁体   English

输入值不响应“keyup”事件

[英]input value not responding to “keyup” event

I am having problem with the following code.我对以下代码有问题。 It is a simple To Do app with Javascript.这是一个简单的待办事项应用程序,带有 Javascript。 Following a tutorial, followed to the t.跟着教程,跟着t。 My app isn't working the way it is supposed to.我的应用程序没有按应有的方式工作。 When I press the enter key the input value should be added to the list and it is not.当我按下回车键时,输入值应该被添加到列表中,而不是。 I can't find any flaw in the code.我在代码中找不到任何缺陷。

Also when I call the function manually addToDo("read");另外,当我手动调用 function 时addToDo("read"); it shows up alright.它显示正常。 But the enter button is not responding.但是输入按钮没有响应。 Any advice will be appreciated.任何建议将被认真考虑。

document.addEventListener("keyup", function(event) {
    if (event.key === 13) {
        const toDo = input.value;
        if (toDo) {
            addToDo(toDo);
        } //end if toDo
    } // end if event.key

});

It doesn't work because you're not checking for the proper key value on the keyup event: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values它不起作用,因为您没有在keyup事件上检查正确的keyhttps://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

You can check for the 'Enter' key on the keyup event like so:您可以像这样检查keyup事件中的“Enter”键:

txtTodo.addEventListener('keyup', (e) => {
  if (e.key === 'Enter') {
    console.log(e.target.value);
  }
});

A live example can be found here:一个活生生的例子可以在这里找到:
https://jsfiddle.net/dbkf53w2/ https://jsfiddle.net/dbkf53w2/

 function addToDo(val) { console.log(val); } document.querySelector('#input-field').addEventListener('keyup', function (event) { if (event.key === 'Enter') { const toDo = event.target.value; if (toDo) { addToDo(toDo); } //end if toDo } // end if event.key });
 <input type="text" id="input-field">

event.key value has a string value. event.key值有一个字符串值。 Try with 'Enter' rather than 13. Number is keyCode.尝试使用“Enter”而不是 13。数字是 keyCode。 When trying to console event.keyCode then it shows numbers.当试图控制event.keyCode时,它会显示数字。

 document.addEventListener("keyup", function(event){ console.log(event.keyCode); if(event.key=== 'Enter'){ //const toDo = input.value; //if(toDo){ // addToDo(toDo); console.log('Enter') //}//end if toDo }// end if event.key })
 <div>Push 'Enter' please</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM