【问题标题】: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】:

你需要做两件事:

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

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>

【讨论】:

    【解决方案2】:

    请看这里: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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2017-01-29
      • 2020-01-21
      相关资源
      最近更新 更多