gpt4 book ai didi

javascript - for 循环中仅打开第三个帖子

转载 作者:行者123 更新时间:2023-11-28 17:18:26 24 4
gpt4 key购买 nike

下面是一些示例代码,用于显示存储在数组中的文档上的帖子:

var posts = [{
title: "Post One",
text: "This is the first post."
},
{
title: "Post Two",
text: "This is the second post."
},
{
title: "Post Three",
text: "This is the third and final post."
}
];

for (var i in posts) {
var post = document.createElement("div");

post.addEventListener("click", function() {
post.classList.toggle("expanded");
});

var title = document.createElement("h2");
title.innerText = posts[i].title;

var text = document.createElement("p");
text.innerText = posts[i].text;

post.appendChild(title);
post.appendChild(text);

document.body.appendChild(post);
}
div {
border: 1px solid #000000;
margin: 10px;
padding: 10px;
background-color: #ffffff;
}

div.expanded {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}
Click a post to expand it:

但是,当我单击任何帖子时,它总是打开最后一个帖子。

关于如何解决这个问题有什么建议吗?

谢谢。

最佳答案

这是因为 var 的范围。替换var post = document.createElement("div");let post = document.createElement("div");

var posts = [{
title: "Post One",
text: "This is the first post."
},
{
title: "Post Two",
text: "This is the second post."
},
{
title: "Post Three",
text: "This is the third and final post."
}
];

for (var i in posts) {
let post = document.createElement("div");
post.addEventListener("click", function() {
post.classList.toggle("expanded");
});

var title = document.createElement("h2");
title.innerText = posts[i].title;

var text = document.createElement("p");
text.innerText = posts[i].text;

post.appendChild(title);
post.appendChild(text);

document.body.appendChild(post);
}
div {
border: 1px solid #000000;
margin: 10px;
padding: 10px;
background-color: #ffffff;
}

div.expanded {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}

关于javascript - for 循环中仅打开第三个帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com