只有第三个帖子打开循环



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

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;
}

在事件侦听器中将post更改为this

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() {
		this.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:

问题出在点击事件侦听器上。您需要传递此引用而不是发布:

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

相关内容

  • 没有找到相关文章

最新更新