【发布时间】:2023-01-03 05:56:08
【问题描述】:
我目前正在研究简单的事件监听器。我创建了一个页面,该页面在输入时从文本框中获取输入,并将新的 LI 附加到一个空的 UL。
const form = document.querySelector('#firstForm');
const data = document.querySelector('#info');
const list = document.querySelector('#list');
const para = document.querySelector('#live');
const entries = document.querySelectorAll('li');
form.addEventListener("input", function (e) {
e.preventDefault();
console.log("======");
console.log(`${data.value}`);
const input = data.value;
const newLI = document.createElement('LI');
newLI.innerText = input;
para.innerText = input;
list.append(newLI);
console.log("======");
// form.reset();
const listArr = Array.from(entries)
});
<h1>My form with live update</h1>
<p id="live"></p>
<form action="/fourohfour" id="firstForm">
<input type="text" id="info">
</form>
<h2>Submitted Data</h2>
<ul id="list">
</ul>
因此,我的问题是:我正在尝试创建一个新功能,该功能将涉及迭代所有新创建的 LI。
但是,当我去获取 nodeList 时,document.querySelectorAll('LI') 返回空。
如果需要控制台访问,这里是一个实时 GitHub 站点的链接 => OperationNorthwoods.github.io
【问题讨论】:
-
问题是当你最初声明entries = document.querySelectorAll('li')您正在为结果设置条目,因为它们是正确的。它不会更新 DOM。在您的输入事件侦听器中,您应该参考的地方entries = document.querySelectorAll('li').
-
当放置在事件侦听器中时,const entries = document.querySelectorAll('li');在 JS 控制台中返回为未定义。顺序(即:事件侦听器函数代码的底部或顶部)重要吗?
-
我在下面创建了一个有效的答案。它可能应该在底部,这样它会在添加它们时抓住所有这些。
-
为什么不更新条目列表
标签: javascript html loops for-loop append