将剪贴板中的代码粘贴到多个输入字段中

Ars*_*eer 4 html javascript typescript

我一直在寻找 Vanilla Javascript 解决方案,将代码复制粘贴到多个输入字段中。

我在互联网上找到了解决方案,但都是基于 jQuery 的。 这是 jQuery 解决方案

<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
Run Code Online (Sandbox Code Playgroud)

我从电子邮件中复制了此代码,并将代码粘贴到任何输入字段中,它将在每个字段中一一粘贴完整的代码。然后使用预先保存的代码验证此代码。我正在寻找在普通 JavaScript中粘贴然后收集和验证代码。

JKi*_*rtz 9

这是一种方法,可以轻松修改它以处理特定的文本输入,但这可以确保页面上的每个文本输入从剪贴板获取相同的数据。

旁注:querySelectorAll返回 anodelist而不是数组,您可以在 a 中[].forEach.call使用数组的方法。forEachnodelist

// Listen to paste on the document
document.addEventListener("paste", function(e) {
  // if the target is a text input
  if (e.target.type === "text") {
   var data = e.clipboardData.getData('Text');
   // split clipboard text into single characters
   data = data.split('');
   // find all other text inputs
   [].forEach.call(document.querySelectorAll("input[type=text]"), (node, index) => {
      // And set input value to the relative character
      node.value = data[index];
    });
  }
});
Run Code Online (Sandbox Code Playgroud)
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
<input type="text" maxlength="1">
Run Code Online (Sandbox Code Playgroud)