我正在尝试将数据从输入字段推送到数组,然后将其显示在li中。但只有我能在控制台中实现数组。我的for循环还好吗?
let btn = document.getElementById('btn-sub');
btn.addEventListener('click', addToDo);
function addToDo(e) {
e.preventDefault();
let value = document.getElementById('field').value;
let values = [];
values.push(value);
for (var index = 0; index < values.length; index++) {
var element = values[index];
let li = document.getElementsByClassName('collection-item');
li.innerText += element;
}
}
&#13;
<div class="container">
<div class="row">
<div class="input-field col s10">
<input id="field" type="text" class="validate">
<label for="password">To do!</label>
</div>
<div class="input-field col s2">
<a class="waves-effect waves-light btn" id="btn-sub">button</a>
</div>
</div>
</div>
<ul class="collection">
<li class="collection-item">
</li>
</ul>
&#13;
答案 0 :(得分:0)
执行document.getElementsByClassName('collection-item')
时,它会返回一个节点数组,您必须选择要使用此数组中的哪个项目。因此,在您的情况下,它应该是let li = document.getElementsByClassName('collection-item')[index]
,例如document.getElementsByClassName('collection-item')[0]
将从所有节点中选择第一个项目。以下是工作示例(无需重构代码):
let btn = document.getElementById('btn-sub');
btn.addEventListener('click', addToDo);
function addToDo(e) {
e.preventDefault();
let value = document.getElementById('field').value;
let values = [];
values.push(value);
for (var index = 0; index < values.length; index++) {
var element = values[index];
let li = document.getElementsByClassName('collection-item')[index];
li.innerText += element;
}
}
<div class="container">
<div class="row">
<div class="input-field col s10">
<input id="field" type="text" class="validate">
<label for="password">To do!</label>
</div>
<div class="input-field col s2">
<a class="waves-effect waves-light btn" id="btn-sub">button</a>
</div>
</div>
</div>
<ul class="collection">
<li class="collection-item">
</li>
</ul>
“好的,当我想每次使用来自输入字段的新数据获得新的li时,如何使这项工作?不会覆盖以前的li”
我简化了一些代码,在这种情况下你并不需要数组和循环,因为你只有一个输入:
let btn = document.getElementById('btn-sub');
btn.addEventListener('click', addToDo);
function addToDo() {
let value = document.getElementById('field').value;
let node = document.createElement("LI")
document.getElementsByClassName('collection')[0].appendChild(node).innerText = value;
}
<div class="container">
<div class="row">
<div class="input-field col s10">
<input id="field" type="text" class="validate">
<label for="password">To do!</label>
</div>
<div class="input-field col s2">
<a class="waves-effect waves-light btn" id="btn-sub">button</a>
</div>
</div>
</div>
<ul class="collection"></ul>
如果有什么不清楚,请随意询问。