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

时间:2018-10-23 17:42:55

标签: javascript html

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

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:

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

关于如何解决此问题的任何建议?

谢谢。

3 个答案:

答案 0 :(得分:3)

这是因为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;
}

答案 1 :(得分:0)

在事件监听器中将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:

答案 2 :(得分:0)

问题与点击事件监听器有关。您需要传递此引用而不是post:

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