我一直在寻找 Vanilla Javascript 解决方案,将代码复制粘贴到多个输入字段中。
我在互联网上找到了解决方案,但都是基于 jQuery 的。这是 jQuery 解决方案 https://stackoverflow.com/questions/11804064/pasting-multiple-numbers-over-multiple-input-fields
<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">
我从电子邮件中复制了此代码,并将代码粘贴到任何输入字段中,它将在每个字段中一一粘贴完整的代码。然后使用预先保存的代码验证此代码。
粘贴然后收集并验证代码普通 JavaScript就是我正在寻找的。
这是一种方法,可以轻松修改它以处理特定的文本输入,但这可以确保页面上的每个文本输入从剪贴板获取相同的数据。
边注:querySelectorAll
返回一个nodelist
您可以使用而不是数组[].forEach.call
使用数组的forEach
方法在一个nodelist
.
// 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];
});
}
});
<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">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)