繁体   English   中英

如何在动态创建的输入标签上捕获“输入”键 - Vanilla JS

[英]How to capture 'enter' key on dynamically created input tag - Vanilla JS

我有一个动态创建的输入标签。 我想听它的 enter key keyup 我搜索了互联网,发现只有 JQUERY 解决方案。 我更喜欢香草 Javascirpt。

我尝试了以下代码,这似乎不起作用,因为我无法 select 特定元素

document.addEventListener("keyup", function(event) {

    if (event.keyCode === 13) {

    }
});

谢谢,罗伯·威尔逊

你需要做两件事:

  1. 将事件侦听器添加到输入的容器中:表单、div、文档等...
  2. 在侦听器内部,检查输入键和预期的 class

 const VK_ENTER = 13; const handleEnterKey = ({ keyCode, target }) => { // Only if the enter key is pressed and the target is an "enter-able" input if (keyCode === VK_ENTER && target.classList.contains('enter-able')) { console.log(target.value); } }; // Add listener to the container that holds the inputs const localScope = document.querySelector('.local-scope'); localScope.addEventListener('keyup', handleEnterKey); // Added to document body after assigning the event listener const input = document.createElement('input'); input.setAttribute('type', 'text'); input.setAttribute('placeholder', 'Dynamic...'); input.classList.add('enter-able'); localScope.append(input);
 .local-scope { display: flex; flex-direction: column; }.enter-able { margin-bottom: 0.5em; }
 <div class="local-scope"> <input type="text" class="enter-able" placeholder="Static..." /> </div>

见这里: https://developer.mozilla.org/en-US/docs/Web/API/Document/keyup_event

 const ENTER_BUTTON_KEY_CODE = 13; document.addEventListener('keyup', event => { if (event.keyCode === ENTER_BUTTON_KEY_CODE) { console.log('Enter was pressed. Yay;'). } else { console.error(`${event.code} was pressed;`); } });
 Press enter

暂无
暂无

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

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