当您输入表单字段编号时,我创建了一个程序,如果您跌倒,可以插入一个加号输入框,删除。一个问题是我们有一个for循环,你可以在其中收集"验证" class是(这些表单字段)。 onblur事件添加功能,但我无法解决那个添加新元素给程序考虑的问题。我试过,我做了一个包含新元素到数组的数组,但由于for循环因此在事件之外,如果你添加它,你就无能为力。
如果有人可以在那种情况下提供帮助,那就不会解决这个问题,我真的很感激! (提供了一个代码,只有一个测试,专门针对这个问题。)
function onlyNumber(e) {
var x = e.keyCode;
if ((x >= 49 && x <= 57) || x === 9 || x === 8 || x === 46 || (x >= 97 && x <= 105)) {
return true;
} else {
e.preventDefault();
}
}
function initOnlyNumber() {
var el = document.querySelectorAll('.onlynumber');
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('keydown', onlyNumber, false);
}
}
var childNumber = document.querySelector('.childNumber');
childNumber.onkeyup = function() {
var childNumberValue = childNumber.value;
var childrens = document.querySelector('.childrens');
var inputLengths = document.querySelectorAll('.kids');
var inputLength = '';
var element = '';
for (var i = 0; i < inputLengths.length; i++) {
var inputLength = inputLengths.length;
var element = inputLengths[i];
}
var arrayElement = [];
for (var i = inputLength; i < childNumberValue; i++) {
var newElement = document.createElement('input');
newElement.classList.add('kids');
newElement.classList.add('validate');
newElement.setAttribute('name', 'child-' + (i + 1));
newElement.setAttribute('data-name', 'child-' + (i + 1));
childrens.appendChild(newElement);
}
if (inputLength == 1) {
if (childNumberValue == '') {
childrens.removeChild(childrens.lastChild);
}
}
if (childNumberValue > 0) {
for (var i = inputLength; i > childNumberValue; i--) {
childrens.removeChild(childrens.lastChild);
}
}
}
var validates = document.querySelectorAll('.validate');
for (var i = 0; i < validates.length; i++) {
var validate = validates[i];
validate.onblur = function(event) {
obj = this;
console.log(obj);
}
}
window.onload = function() {
initOnlyNumber();
}
&#13;
body {
margin: 20px;
padding: 0;
}
*:link,
*:hover,
*:visited,
*:focus {
outline: none;
}
input:-webkit-autofill {
color: #fff;
-webkit-box-shadow: 0 0 0px 1000px #4caf50 inset;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input {
background-color: #4caf50;
border: 1px solid #555;
color: #fff;
padding: 10px;
width: 50px;
}
.childrens {
display: inline-block;
}
.childrens input {
display: inline-block;
margin-left: 15px;
}
.childNumber {
background-color: #555;
}
&#13;
<form action="">
<input class="validate onlynumber" name="name" type="text">
<br />
<br />
<input class="validate onlynumber" name="email" type="text">
<br />
<br />
<input class="validate onlynumber" name="tax" type="text">
<br />
<br />
<input class="validate onlynumber" name="phone" type="text">
<br />
<br />
<input class="childNumber onlynumber" name="childNumber" type="text" maxlength="1">
<div class="childrens"></div>
</form>
&#13;