【问题标题】:How to capture 'enter' key on dynamically created input tag - Vanilla JS如何在动态创建的输入标签上捕获“输入”键 - Vanilla JS
【发布时间】:2021-05-07 14:27:18
【问题描述】:
我有一个动态创建的输入标签。我想听它的输入键keyup。我搜索了互联网,发现只有 JQUERY 解决方案。我更喜欢 Vanilla Javascirpt。
我尝试了以下代码,但似乎无法正常工作,因为我无法选择特定元素
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
}
});
谢谢,罗伯·威尔逊
【问题讨论】:
标签:
javascript
addeventlistener
event-listener
onkeyup
【解决方案1】:
你需要做两件事:
- 将事件侦听器添加到输入容器:表单、div、文档等...
- 在侦听器内部,检查输入键和预期的类
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>