javascript - Why does my nodelist contain 0 items when console logged from my JS file?
问题描述
The JS code that I'm concerned with is this:
const modals=document.querySelectorAll('.modal');
const modalsArray=[...modals];
console.log(modalsArray);
document.addEventListener('click', function (e) {
e.stopPropagation();
e.preventDefault();
if (e.target.classList.contains("item")) {
itemIndex=e.target.classList.item(1);
const modals=document.querySelectorAll('.modal');
const modalsArray=[...modals];
console.log(itemIndex);
console.log(modalsArray);
modalsArray.filter(function (modal) {
if (modal.classList.item(1)===itemIndex) {
modal.classList.add('on');
modalContainer.classList.remove('off');
modalContainer.classList.add('on');
}
})
}
});
const arrow=document.querySelectorAll('.arrow');
const arrowArray=[...arrow];
console.log(arrowArray);
Whenever I console log the modalsArray or the arrowArray from my JS file, the array shows up empty. But I found that if I write out the code from scratch in the console to make the arrays, then all the items in the array show up properly.
So why is this happening? Why is an empty array currently showing up on my console? Does it have to do with scope or something?
When I put the modalsArray inside the eventlistener, and I click the respective target, an array will show properly and the rest of the code in that eventlistener works properly.
I'm noticing the same thing with the arrowArray and realized these two elements are having the same problem. I figured I should ask then because something is definitely up.
So why is an empty array showing up for both of these elements as seen in the image?
Check out my fiddle for more information: https://jsfiddle.net/apasric4/kvs25wbL/3/
解决方案
您的控制台语句甚至在获取数据之前就已执行。我将它们链接在另一个“then”函数(承诺链接)中,如下所示。这样,您的控制台语句在您的结果被解析为 hmtl 后运行。
https://jsfiddle.net/v83zqofp/1/
function generateHTML (data) {
fetchData(data)
.then(function(data){
let results=data.results;
return results.map(function(result,index){
-------------
main.lastElementChild.insertAdjacentHTML('afterend', html);
modalContainer.insertAdjacentHTML('beforeend', overlayHtml);
})
}).then (function (data) {
const modals=document.querySelectorAll('.modal');
const modalsArray=[...modals];
console.log(modalsArray);
const arrow=document.querySelectorAll('.arrow');
const arrowArray=[...arrow];
console.log(arrowArray);
})
}
推荐阅读
- java - Spring Boot 应用程序未在 openWRT 上运行
- oracle - 连接到通过同一端口侦听的同一台计算机上的数据库时出现 ORA-12505 错误
- r - 显示实际删除的空日期的绘图
- cmake - 为什么我不能使用 CLion 配置 CMake 目标(没有可运行的内容)?
- excel - 如何模仿 Outlook 应用程序中的“收件人”按钮以生成“选择名称”对话框以将电子邮件地址检索到 Excel?
- python - 尝试在 Python 中做傅里叶级数的问题
- go - 被白色半透明覆盖的参数区域在vs代码中不会触发代码提示,如何解决?
- swift - 我可以将 AWS Amplify 与独立的 WatchOS 应用程序一起使用吗?
- haskell - Haskell:使用“putStr”时出现神秘的“数组索引错误”
- sql - 我被这个查询困住了