问题描述
我已经尝试过了,因为所有输入都有一个父级,这在最后一个元素处添加;如果我用externalHtml做到这一点,会破坏下一个焦点
const inputArr = Array.from(document.querySelectorAll('input'));
const span = document.createElement('span');
const text = document.createTextNode('-');
span.appendChild(text);
for (let input of inputArr) {
console.log(input.parentElement);
input.parentElement.insertBefore(span,input.nextElementSibling)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="wrapper">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</div>
</body>
</html>
包装:https://www.npmjs.com/package/ng-otp-input,我在使用此包装,我想在每个输入(最后一个输入除外)之后添加span元素。
当前输出:
必需的输出:
解决方法
您试图在循环中两次添加相同的元素。您应该为每次迭代创建一个新的。另外,如果您使用常规的for
循环而不是 foreach ,则可以从0循环到inputArr.length - 1
。这样,您就不会在最后的输入中添加span
元素。
const inputArr = Array.from(document.querySelectorAll('input'));
for (let i = 0; i < inputArr.length - 1; i ++) {
const span = document.createElement('span');
const text = document.createTextNode('-');
const input = inputArr[i];
span.appendChild(text);
console.log(input.parentElement);
input.parentElement.insertBefore(span,input.nextElementSibling)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="wrapper">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</div>
</body>
</html>
PS 为了更干净地实现这一目标,我非常喜欢Qurben's answer。它正确使用了数组函数。
作为奖励,这是几乎一行的数组函数。因为谁不喜欢复杂的数组函数行? / s
Array.from(document.querySelectorAll('input'))
.filter((item,index,array) => index !== array.length - 1)
.forEach(item => {
item.parentElement.insertBefore(
document.createElement('span')
.appendChild(document.createTextNode('-')),item.nextElementSibling)
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="wrapper">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</div>
</body>
</html>
,
您可以使用.pop()
从所选数组中删除最后一个元素。跨度的创建也应该在数组内部进行,因为您要有多个跨度。
const inputArr = Array.from(document.querySelectorAll('input'));
inputArr.pop() // Remove the last element
for (let input of inputArr) {
const span = document.createElement('span');
const text = document.createTextNode(' - ');
span.appendChild(text);
console.log(input.parentElement);
input.parentElement.insertBefore(span,input.nextElementSibling)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="wrapper">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</div>
</body>
</html>
您还可以使用.slice(0,-1)
(从零开始选择,直到最后一个元素)。此方法不会更改基础数组。 for循环将类似于以下内容。 (删除了.pop()
呼叫)
for (let input of inputArr.slice(0,-1))